diff --git a/backend/config.py b/backend/config.py index f23517c76e9d1cd2172086124fd95b4144621e0d..0573d9e34c406b1d012fb56ed4b7525934b640e8 100644 --- a/backend/config.py +++ b/backend/config.py @@ -39,6 +39,6 @@ raw_cors = os.getenv("CORS_ORIGINS", "*") CORS_ORIGINS: list[str] = ["*"] if raw_cors == "*" else [c.strip() for c in raw_cors.split(",") if c.strip()] # --- Signal thresholds --- -SIGNAL_LONG_THRESHOLD: int = 4 -SIGNAL_SHORT_THRESHOLD: int = -4 +SIGNAL_LONG_THRESHOLD: int = 3 +SIGNAL_SHORT_THRESHOLD: int = -3 MAX_CONVICTION: int = 10 diff --git a/backend/database/db.py b/backend/database/db.py index 90b1f4ad8ee7cee8528ebac2390518ed4042c0b7..035ec2b172fd2904407b519bd80ad4cf8b6145b2 100644 --- a/backend/database/db.py +++ b/backend/database/db.py @@ -7,7 +7,9 @@ asyncio.to_thread() called from async FastAPI routes / background tasks. import json import logging +import math import asyncio +import threading from contextlib import contextmanager from typing import Any, Generator @@ -31,6 +33,22 @@ logger = logging.getLogger(__name__) _pool: ConnectionPool | None = None _mem = memory_store +_predictions_table_lock = threading.Lock() + + +def _sanitize_json_payload(obj: Any) -> Any: + """Replace non-finite floats (NaN/Inf) with None so PostgreSQL JSONB never fails on NaN.""" + if isinstance(obj, float): + return obj if math.isfinite(obj) else None + if isinstance(obj, dict): + return {k: _sanitize_json_payload(v) for k, v in obj.items()} + if isinstance(obj, (list, tuple)): + return [_sanitize_json_payload(v) for v in obj] + return obj + + +def _safe_json_dumps(obj: Any) -> str: + return json.dumps(_sanitize_json_payload(obj), allow_nan=False) def get_pool() -> ConnectionPool: @@ -413,7 +431,7 @@ def db_save_signal(symbol: str, timeframe: str, direction: str, conviction: int, cur.execute( """INSERT INTO signals (symbol, timeframe, direction, conviction, signal_data) VALUES (%s, %s, %s, %s, %s)""", - (symbol, timeframe, direction, conviction, json.dumps(signal_data)), + (symbol, timeframe, direction, conviction, _safe_json_dumps(signal_data)), ) @@ -692,7 +710,7 @@ def db_create_journal_entry(data: dict) -> dict: """Insert a new trade record into trade_journal.""" if not DATABASE_URL: return _mem.create_journal_entry(data) - snapshot_json = json.dumps(data.get("snapshot_data") or {}) + snapshot_json = _safe_json_dumps(data.get("snapshot_data") or {}) query = """ INSERT INTO trade_journal ( symbol, bias, entry_zone, stop_loss, take_profit, risk_reward, @@ -816,7 +834,7 @@ def db_get_journal_stats() -> dict: COUNT(*) FILTER (WHERE status = 'HIT_SL') as hit_sl, COUNT(*) FILTER (WHERE status = 'PENDING') as pending, COUNT(*) FILTER (WHERE status = 'CANCELLED') as cancelled, - COUNT(*) FILTER (WHERE status = 'HIT_SL' AND audited = FALSE) as unaudited_sl + COUNT(*) FILTER (WHERE status = 'HIT_SL' AND COALESCE(audited, FALSE) = FALSE) as unaudited_sl FROM trade_journal; """) row = cur.fetchone() or {} @@ -851,7 +869,7 @@ def db_get_unaudited_failed_trades(limit: int = 10) -> list[dict]: cur.execute( """ SELECT * FROM trade_journal - WHERE status = 'HIT_SL' AND audited = FALSE + WHERE status = 'HIT_SL' AND COALESCE(audited, FALSE) = FALSE ORDER BY created_at ASC LIMIT %s; """, @@ -966,11 +984,14 @@ def _ensure_predictions_table(cur: Any, conn: Any) -> None: global _predictions_table_ensured if _predictions_table_ensured: return - cur.execute(CREATE_SIGNAL_PREDICTIONS_TABLE) - cur.execute(CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX) - cur.execute(CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX) - conn.commit() - _predictions_table_ensured = True + with _predictions_table_lock: + if _predictions_table_ensured: + return + cur.execute(CREATE_SIGNAL_PREDICTIONS_TABLE) + cur.execute(CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX) + cur.execute(CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX) + conn.commit() + _predictions_table_ensured = True def db_insert_signal_prediction(data: dict) -> dict: @@ -1000,7 +1021,7 @@ def db_insert_signal_prediction(data: dict) -> dict: float(data.get("stop_loss", 0.0)), float(data.get("tp1", 0.0)), float(data.get("tp2", 0.0)), - json.dumps(data.get("factor_scores") or {}), + _safe_json_dumps(data.get("factor_scores") or {}), data.get("expires_at"), ), ) diff --git a/backend/database/memory_store.py b/backend/database/memory_store.py index cab6c43b57f2a61b4a4f900c3cb1bafcba2e6358..a6e1d5a29bdc62ef4e3e73a2f8060db2c5f47286 100644 --- a/backend/database/memory_store.py +++ b/backend/database/memory_store.py @@ -385,6 +385,11 @@ class InMemoryDatabaseStore: entry["status"] = st entry["outcome_note"] = note entry["outcome_at"] = None if st == "PENDING" else _utc_now_iso() + if st == "PENDING": + entry["failure_tag"] = None + entry["exit_price"] = None + entry["holding_duration_seconds"] = None + entry["audited"] = False if failure_tag is not None: entry["failure_tag"] = failure_tag if exit_price is not None: @@ -531,6 +536,8 @@ class InMemoryDatabaseStore: if isinstance(created_str, str): try: c_dt = datetime.fromisoformat(created_str.replace("Z", "+00:00")) + if c_dt.tzinfo is None: + c_dt = c_dt.replace(tzinfo=now_dt.tzinfo) if (now_dt - c_dt).total_seconds() < cooldown_hours * 3600: return copy.deepcopy(r) except ValueError: @@ -550,6 +557,8 @@ class InMemoryDatabaseStore: if isinstance(created_str, str): try: c_dt = datetime.fromisoformat(created_str.replace("Z", "+00:00")) + if c_dt.tzinfo is None: + c_dt = c_dt.replace(tzinfo=now_dt.tzinfo) if (now_dt - c_dt).total_seconds() > cutoff_sec: continue except ValueError: @@ -603,7 +612,11 @@ def compute_accuracy_summary_from_rows(rows: list[dict[str, Any]], days: int = 3 if not isinstance(f_scores, dict): continue for f_name, raw_val in f_scores.items(): - score = int(raw_val.get("score", 0)) if isinstance(raw_val, dict) else int(raw_val or 0) + raw_score = raw_val.get("score", 0) if isinstance(raw_val, dict) else raw_val + try: + score = int(float(raw_score)) if raw_score is not None else 0 + except (TypeError, ValueError): + score = 0 if score == 0: continue b = factor_buckets.setdefault(f_name, {"aligned": [], "opposing": []}) diff --git a/backend/engine/backtester.py b/backend/engine/backtester.py index 819ff21c1cd7c73a4cbd7eddbd67188e462219d5..0596823080a796af28aaba220e90df5d3454d18f 100644 --- a/backend/engine/backtester.py +++ b/backend/engine/backtester.py @@ -43,11 +43,15 @@ def _aggregate_higher_tf(candles_1h: list[dict], group_hours: int) -> list[dict] "close": float(c["close"]), "volume": float(c.get("volume", 0.0)), } + if c.get("taker_buy_volume") is not None: + cur_bar["taker_buy_volume"] = float(c["taker_buy_volume"]) else: cur_bar["high"] = max(cur_bar["high"], float(c["high"])) cur_bar["low"] = min(cur_bar["low"], float(c["low"])) cur_bar["close"] = float(c["close"]) cur_bar["volume"] += float(c.get("volume", 0.0)) + if c.get("taker_buy_volume") is not None: + cur_bar["taker_buy_volume"] = cur_bar.get("taker_buy_volume", 0.0) + float(c["taker_buy_volume"]) if cur_bar is not None: grouped.append(cur_bar) diff --git a/backend/engine/data_collector.py b/backend/engine/data_collector.py index 1267266ca5df498645b5e188f0ce18d534b90455..ca4089122c1a90b91cc940f78b1f29d29d748c63 100644 --- a/backend/engine/data_collector.py +++ b/backend/engine/data_collector.py @@ -20,6 +20,7 @@ from typing import Any import httpx from config import BYBIT_BASE_URL, PROXY_URL +from engine.symbol_resolver import strip_multiplier_prefix from exchanges.binance import BinanceClient from exchanges.bybit import BybitClient from exchanges.okx import OKXClient @@ -32,12 +33,22 @@ logger = logging.getLogger(__name__) _SPOT_VERIFICATION_CACHE: dict[str, tuple[bool, float]] = {} _spot_cache_lock = asyncio.Lock() _SPOT_HTTP_CLIENT: httpx.AsyncClient | None = None +_SPOT_HTTP_LOOP: asyncio.AbstractEventLoop | None = None def _get_spot_http_client() -> httpx.AsyncClient: - """Return a shared persistent AsyncClient for spot existence probes (avoids repeated TLS handshakes).""" - global _SPOT_HTTP_CLIENT - if _SPOT_HTTP_CLIENT is None or _SPOT_HTTP_CLIENT.is_closed: + """Return a loop-safe persistent AsyncClient for spot existence probes.""" + global _SPOT_HTTP_CLIENT, _SPOT_HTTP_LOOP + try: + current_loop = asyncio.get_running_loop() + except RuntimeError: + current_loop = None + + loop_changed = ( + _SPOT_HTTP_LOOP is not None + and (_SPOT_HTTP_LOOP.is_closed() or (current_loop is not None and _SPOT_HTTP_LOOP is not current_loop)) + ) + if _SPOT_HTTP_CLIENT is None or _SPOT_HTTP_CLIENT.is_closed or loop_changed: kwargs: dict[str, Any] = { "timeout": 2.5, "verify": True, @@ -50,15 +61,16 @@ def _get_spot_http_client() -> httpx.AsyncClient: if PROXY_URL: kwargs["proxy"] = PROXY_URL _SPOT_HTTP_CLIENT = httpx.AsyncClient(**kwargs) + _SPOT_HTTP_LOOP = current_loop return _SPOT_HTTP_CLIENT def _clean_spot_symbol(symbol: str) -> str: """ - Strip futures multiplier prefixes (1000, 10000, 1000000, k) to match spot tickers. - e.g. 1000PEPEUSDT -> PEPEUSDT, 1000SHIBUSDT -> SHIBUSDT, 1000BONKUSDT -> BONKUSDT + Strip futures multiplier prefixes (1000, 10000, 1000000, known meme k-prefixes) + to match spot tickers without mangling tokens like KAVAUSDT or KASUSDT. """ - return re.sub(r'^(1000000000|1000000|100000|10000|1000|k)', '', symbol, flags=re.IGNORECASE).upper() + return strip_multiplier_prefix(symbol) async def check_spot_market_exists(symbol: str) -> bool: @@ -68,17 +80,18 @@ async def check_spot_market_exists(symbol: str) -> bool: - If verified True: cached permanently in memory. - If False: re-checks automatically every 1 hour in case a spot market is newly listed. """ + sym = symbol.upper().strip().replace("/", "").replace("-", "") now = time.time() async with _spot_cache_lock: - if symbol in _SPOT_VERIFICATION_CACHE: - cached_has_spot, timestamp = _SPOT_VERIFICATION_CACHE[symbol] + if sym in _SPOT_VERIFICATION_CACHE: + cached_has_spot, timestamp = _SPOT_VERIFICATION_CACHE[sym] # Permanent True or cached False within 1 hour if cached_has_spot or (now - timestamp < 3600): return cached_has_spot - clean_symbol = _clean_spot_symbol(symbol) - symbols_to_try = [symbol] - if clean_symbol != symbol and clean_symbol.endswith("USDT"): + clean_symbol = _clean_spot_symbol(sym) + symbols_to_try = [sym] + if clean_symbol and clean_symbol != sym and clean_symbol.endswith(("USDT", "USDC", "USD", "BUSD", "EUR")): symbols_to_try.append(clean_symbol) client = _get_spot_http_client() @@ -108,9 +121,12 @@ async def check_spot_market_exists(symbol: str) -> bool: async def _check_okx() -> bool: for sym in symbols_to_try: - if sym.endswith("USDT"): - base = sym[:-4] - inst_id = f"{base}-USDT" + inst_id = None + for quote in ("USDT", "USDC", "USD", "BUSD", "EUR"): + if sym.endswith(quote) and len(sym) > len(quote): + inst_id = f"{sym[:-len(quote)]}-{quote}" + break + if inst_id: try: r = await client.get(f"https://www.okx.com/api/v5/public/instruments?instType=SPOT&instId={inst_id}") if r.status_code == 200: @@ -125,7 +141,7 @@ async def check_spot_market_exists(symbol: str) -> bool: has_spot = any(res is True for res in results if not isinstance(res, Exception)) async with _spot_cache_lock: - _SPOT_VERIFICATION_CACHE[symbol] = (has_spot, now) + _SPOT_VERIFICATION_CACHE[sym] = (has_spot, now) return has_spot @@ -189,14 +205,16 @@ class DataCollector: # Hyperliquid On-Chain DEX async def _fetch_hl(): try: - market_data, orderbook = await asyncio.gather( + market_data, orderbook, hl_trades = await asyncio.gather( self._hyperliquid.get_market_data(symbol), self._hyperliquid.get_orderbook(symbol, depth=20), + self._hyperliquid.get_recent_trades(symbol), return_exceptions=True, ) if isinstance(market_data, Exception) or not market_data: return None market_data["orderbook"] = orderbook if not isinstance(orderbook, Exception) else None + market_data["trades"] = hl_trades if (not isinstance(hl_trades, Exception) and isinstance(hl_trades, list)) else [] return market_data except Exception as exc: logger.debug("[%s] Hyperliquid collect error: %s", symbol, exc) diff --git a/backend/engine/execution/bybit_executor.py b/backend/engine/execution/bybit_executor.py index b9a5c1ca0d92e3815e5bd1a821c5b80712a30b3f..8db1149433528a4eb4351b2a54936008784938db 100644 --- a/backend/engine/execution/bybit_executor.py +++ b/backend/engine/execution/bybit_executor.py @@ -12,6 +12,7 @@ import hashlib import logging import math import os +from decimal import Decimal, InvalidOperation, ROUND_DOWN, ROUND_HALF_UP from typing import Any from urllib.parse import urlencode @@ -57,6 +58,11 @@ class BybitExecutor: async def close(self) -> None: await self._client.aclose() + @staticmethod + def _clean_symbol(symbol: str) -> str: + """Normalize perpetual pair formatting (e.g. BTC/USDT, btc-usdt -> BTCUSDT).""" + return symbol.upper().strip().replace("/", "").replace("-", "") + def _generate_signature(self, timestamp: str, payload_str: str) -> str: """Bybit V5 HMAC-SHA256 signature generator.""" param_str = f"{timestamp}{self.api_key}{self.recv_window}{payload_str}" @@ -77,10 +83,12 @@ class BybitExecutor: } if method.upper() == "GET": - query_str = urlencode(sorted((params or {}).items())) if params else "" + sorted_items = sorted((params or {}).items()) if params else [] + query_str = urlencode(sorted_items) if sorted_items else "" sign = self._generate_signature(timestamp, query_str) headers["X-BAPI-SIGN"] = sign - resp = await self._client.get(path, params=params, headers=headers) + req_path = f"{path}?{query_str}" if query_str else path + resp = await self._client.get(req_path, headers=headers) else: body_str = json.dumps(json_body, separators=(",", ":")) if json_body else "" sign = self._generate_signature(timestamp, body_str) @@ -109,7 +117,8 @@ class BybitExecutor: async def get_wallet_balance(self) -> dict[str, Any]: """Fetch Unified/Futures USDT available balance and total equity.""" data = await self._request("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED"}) - acct_item = data.get("result", {}).get("list", [{}])[0] + acct_list = data.get("result", {}).get("list") or [] + acct_item = acct_list[0] if acct_list else {} coins = acct_item.get("coin", []) usdt_info = next((c for c in coins if c.get("coin") == "USDT"), {}) acct_equity = float(acct_item.get("totalEquity") or 0.0) @@ -126,7 +135,7 @@ class BybitExecutor: async def get_instrument_info(self, symbol: str) -> dict[str, Any]: """Fetch contract precision, tickSize, and lotSize.""" - sym = symbol.upper().strip() + sym = self._clean_symbol(symbol) data = await self._request("GET", "/v5/market/instruments-info", { "category": "linear", "symbol": sym, @@ -153,7 +162,7 @@ class BybitExecutor: async def set_leverage(self, symbol: str, leverage: int) -> bool: """Set cross/isolated leverage for linear contract.""" - sym = symbol.upper().strip() + sym = self._clean_symbol(symbol) lev_str = str(max(1, min(leverage, 100))) try: await self._request("POST", "/v5/position/set-leverage", json_body={ @@ -181,21 +190,42 @@ class BybitExecutor: return len(s.split(".")[1]) return 0 + @classmethod + def _format_num(cls, value: float, step_or_tick: float | None = None) -> str: + """Format price/qty as a plain decimal string without scientific notation.""" + num = 0.0 if value == 0 else float(value) + if step_or_tick and step_or_tick > 0: + precision = cls._get_precision(step_or_tick) + return f"{num:.{precision}f}" + return format(Decimal(str(num)), "f") + @classmethod def _round_step(cls, value: float, step: float) -> float: - """Round down value to the nearest step to satisfy exchange filters.""" + """Round down value to the nearest step using Decimal to avoid IEEE 754 truncation loss.""" if step <= 0: return value precision = cls._get_precision(step) - return round(math.floor(value / step) * step, precision) + try: + d_val = Decimal(str(value)) + d_step = Decimal(str(step)) + steps = (d_val / d_step).to_integral_value(rounding=ROUND_DOWN) + return round(float(steps * d_step), precision) + except (InvalidOperation, ZeroDivisionError): + return round(math.floor((value / step) + 1e-9) * step, precision) @classmethod def _round_tick(cls, value: float, tick: float) -> float: - """Round price to the nearest tick.""" + """Round price to the nearest tick using Decimal precision.""" if tick <= 0: return value precision = cls._get_precision(tick) - return round(round(value / tick) * tick, precision) + try: + d_val = Decimal(str(value)) + d_tick = Decimal(str(tick)) + ticks = (d_val / d_tick).to_integral_value(rounding=ROUND_HALF_UP) + return round(float(ticks * d_tick), precision) + except (InvalidOperation, ZeroDivisionError): + return round(round(value / tick) * tick, precision) async def _place_reduce_only_tp( self, @@ -205,16 +235,18 @@ class BybitExecutor: price: float, tp_level: str, percent: float, + qty_step: float | None = None, + tick_size: float | None = None, ) -> dict[str, Any] | None: """Place a reduce-only Limit TP order with transient position-settle retries.""" - sym = symbol.upper().strip() + sym = self._clean_symbol(symbol) payload = { "category": "linear", "symbol": sym, "side": opposite_side, "orderType": "Limit", - "qty": str(qty), - "price": str(price), + "qty": self._format_num(qty, qty_step), + "price": self._format_num(price, tick_size), "timeInForce": "GTC", "reduceOnly": True, "positionIdx": 0, @@ -246,12 +278,14 @@ class BybitExecutor: tp2_qty: float, tp2_price: float, percent: float, + qty_step: float | None = None, + tick_size: float | None = None, ) -> dict[str, Any]: """ Check a Limit entry order's fill state once and attach reduce-only TP2 upon Filled. Returns terminal/non-terminal status so both single checks and pollers can compose it. """ - sym = symbol.upper().strip() + sym = self._clean_symbol(symbol) params = {"category": "linear", "symbol": sym, "orderId": entry_order_id} resp = await self._request("GET", "/v5/order/realtime", params=params) items = resp.get("result", {}).get("list", []) @@ -264,6 +298,13 @@ class BybitExecutor: order_status = str(items[0].get("orderStatus", "")) if order_status == "Filled": + if qty_step is None or tick_size is None: + try: + inst = await self.get_instrument_info(sym) + qty_step = qty_step or inst.get("qty_step") + tick_size = tick_size or inst.get("tick_size") + except Exception: + pass tp2_order = await self._place_reduce_only_tp( symbol=sym, opposite_side=opposite_side, @@ -271,6 +312,8 @@ class BybitExecutor: price=tp2_price, tp_level="TP2", percent=percent, + qty_step=qty_step, + tick_size=tick_size, ) return { "status": "PLACED" if tp2_order else "FAILED", @@ -287,7 +330,7 @@ class BybitExecutor: async def get_open_position(self, symbol: str) -> dict[str, Any] | None: """Fetch active Bybit linear position for symbol (returns None if size == 0).""" - sym = symbol.upper().strip() + sym = self._clean_symbol(symbol) resp = await self._request("GET", "/v5/position/list", params={"category": "linear", "symbol": sym}) items = resp.get("result", {}).get("list", []) for item in items: @@ -307,7 +350,7 @@ class BybitExecutor: """ Move position Stop Loss to avg_entry_price ± 6 bps fee-buffer rounded to tick_size. """ - sym = symbol.upper().strip() + sym = self._clean_symbol(symbol) inst = await self.get_instrument_info(sym) tick_size = inst["tick_size"] is_buy = side.upper() in ("BUY", "LONG") @@ -317,7 +360,7 @@ class BybitExecutor: "category": "linear", "symbol": sym, "positionIdx": 0, - "stopLoss": str(rounded_be_sl), + "stopLoss": self._format_num(rounded_be_sl, tick_size), "slTriggerBy": "MarkPrice", } await self._request("POST", "/v5/position/trading-stop", json_body=payload) @@ -350,7 +393,7 @@ class BybitExecutor: """ Execute trade setup on Bybit V5 with bracket Stop Loss and custom split TP1/TP2. """ - sym = symbol.upper().strip() + sym = self._clean_symbol(symbol) side_norm = "Buy" if side.upper() in ("BUY", "LONG") else "Sell" opposite_side = "Sell" if side_norm == "Buy" else "Buy" @@ -369,7 +412,8 @@ class BybitExecutor: if not calc_price or calc_price <= 0: # Fallback: fetch current ticker price ticker_data = await self._request("GET", "/v5/market/tickers", {"category": "linear", "symbol": sym}) - calc_price = float(ticker_data.get("result", {}).get("list", [{}])[0].get("lastPrice", 0.0)) + ticker_list = ticker_data.get("result", {}).get("list") or [] + calc_price = float((ticker_list[0] if ticker_list else {}).get("lastPrice") or 0.0) if calc_price <= 0: raise ValueError(f"Tidak dapat menentukan harga acuan untuk {sym}.") @@ -412,14 +456,14 @@ class BybitExecutor: "symbol": sym, "side": side_norm, "orderType": "Market" if order_type.upper() == "MARKET" else "Limit", - "qty": str(total_qty), + "qty": self._format_num(total_qty, qty_step), "timeInForce": "GTC", "positionIdx": 0, # One-way mode - "stopLoss": str(rounded_sl), + "stopLoss": self._format_num(rounded_sl, tick_size), "slTriggerBy": "MarkPrice", } - # Calculate TP split quantities + # Calculate TP split quantities using Decimal subtraction to prevent IEEE 754 precision loss tp1_pct = max(10.0, min(float(tp1_percent), 100.0)) if tp1_pct >= 99.0 or not rounded_tp2: tp1_qty = total_qty @@ -427,20 +471,21 @@ class BybitExecutor: else: raw_tp1_qty = total_qty * (tp1_pct / 100.0) tp1_qty = self._round_step(raw_tp1_qty, qty_step) - tp2_qty = self._round_step(total_qty - tp1_qty, qty_step) + raw_rem_qty = float(Decimal(str(total_qty)) - Decimal(str(tp1_qty))) + tp2_qty = self._round_step(max(0.0, raw_rem_qty), qty_step) if tp1_qty < min_qty or tp2_qty < min_qty: tp1_qty = total_qty tp2_qty = 0.0 # For Limit orders, attach takeProfit directly to the order (with Partial sizing if split) if order_type.upper() == "LIMIT": - order_payload["takeProfit"] = str(rounded_tp1) + order_payload["takeProfit"] = self._format_num(rounded_tp1, tick_size) order_payload["tpTriggerBy"] = "MarkPrice" if tp2_qty > 0: order_payload["tpslMode"] = "Partial" - order_payload["tpSize"] = str(tp1_qty) - if entry_price: - order_payload["price"] = str(self._round_tick(entry_price, tick_size)) + order_payload["tpSize"] = self._format_num(tp1_qty, qty_step) + limit_px_val = entry_price if (entry_price and entry_price > 0) else calc_price + order_payload["price"] = self._format_num(self._round_tick(limit_px_val, tick_size), tick_size) logger.info("[%s] Sending Bybit Entry order: %s", sym, order_payload) entry_resp = await self._request("POST", "/v5/order/create", json_body=order_payload) @@ -495,6 +540,8 @@ class BybitExecutor: price=rounded_tp1, tp_level="TP1", percent=100.0, + qty_step=qty_step, + tick_size=tick_size, ) if placed: tp1_orders_info.append(placed) @@ -507,6 +554,8 @@ class BybitExecutor: price=rounded_tp1, tp_level="TP1", percent=tp1_pct, + qty_step=qty_step, + tick_size=tick_size, ) if placed_tp1: tp1_orders_info.append(placed_tp1) @@ -519,6 +568,8 @@ class BybitExecutor: price=rounded_tp2, tp_level="TP2", percent=round(100.0 - tp1_pct, 1), + qty_step=qty_step, + tick_size=tick_size, ) if placed_tp2: tp1_orders_info.append(placed_tp2) @@ -561,7 +612,7 @@ async def watch_position_tp1_breakeven( Supports both explicit reduce-only TP1 order IDs (Market entry) and bound Limit TP1 triggers (10%-99% split). """ watcher = BybitExecutor(api_key=api_key, api_secret=api_secret, mode=mode, proxy_url=proxy_url) - sym = symbol.upper().strip() + sym = BybitExecutor._clean_symbol(symbol) is_bound = not tp1_order_id or str(tp1_order_id).startswith("bound-") threshold_size = max(0.0, float(total_qty) - (0.5 * float(tp1_qty))) try: diff --git a/backend/engine/fake_detector.py b/backend/engine/fake_detector.py index 30c994e4c1e89f46ca7892369e20ac2ea726fa57..adcfdd78af7afc177b92bf4f4fcb44d4531637b9 100644 --- a/backend/engine/fake_detector.py +++ b/backend/engine/fake_detector.py @@ -33,15 +33,18 @@ def _wick_sweep_detected(candles: list[dict]) -> tuple[bool, str]: # Evaluate completed candles only to confirm real wick sweep and close-back recent = candles[-4:-1] if len(candles) >= 4 else candles[:-1] for c in recent: - close = c.get("close", 0) - if close <= 0: + high = c.get("high") + low = c.get("low") + open_p = c.get("open") + close = float(c.get("close") or 0) + if high is None or low is None or open_p is None or close <= 0: continue - rng = c["high"] - c["low"] + rng = float(high) - float(low) if rng <= 0 or (rng / close) < WICK_RANGE_MIN_PCT: continue - upper_wick = c["high"] - max(c["close"], c["open"]) - lower_wick = min(c["close"], c["open"]) - c["low"] + upper_wick = float(high) - max(close, float(open_p)) + lower_wick = min(close, float(open_p)) - float(low) if (upper_wick / rng) > WICK_DOMINANCE_RATIO: return True, "upper_wick_sweep (Liquidity Grab at Highs)" @@ -56,7 +59,7 @@ def _wash_trade_detected(candles: list[dict]) -> bool: if len(candles) < 20: return False - volumes = [c["volume"] for c in candles[:-2]] + volumes = [float(c["volume"]) for c in candles[:-2] if c.get("volume") is not None] if not volumes: return False avg_vol = sum(volumes) / len(volumes) @@ -66,9 +69,12 @@ def _wash_trade_detected(candles: list[dict]) -> bool: # Check the last completed candles (candles[-3] and candles[-2]), excluding the incomplete forming candle candles[-1] candidates = [candles[-3], candles[-2]] if len(candles) >= 21 else [candles[-2]] for cand in candidates: - if cand["volume"] > avg_vol * MIN_VOLUME_SPIKE_MULTIPLIER: - if cand["open"] > 0: - price_move_pct = abs(cand["close"] - cand["open"]) / cand["open"] + cand_vol = float(cand.get("volume") or 0) + cand_open = float(cand.get("open") or 0) + cand_close = float(cand.get("close") or 0) + if cand_vol > avg_vol * MIN_VOLUME_SPIKE_MULTIPLIER: + if cand_open > 0: + price_move_pct = abs(cand_close - cand_open) / cand_open if price_move_pct < MAX_PRICE_MOVE_FOR_WASHTRADING: return True return False @@ -85,8 +91,8 @@ def _orderbook_imbalance_detected(orderbook: dict | None, cvd_matches_price: boo return False, "" try: - bid_vol = sum(float(p) * float(q) for p, q in bids[:20]) - ask_vol = sum(float(p) * float(q) for p, q in asks[:20]) + bid_vol = sum(float(lvl[0]) * float(lvl[1]) for lvl in (bids or [])[:20] if lvl) + ask_vol = sum(float(lvl[0]) * float(lvl[1]) for lvl in (asks or [])[:20] if lvl) except (ValueError, TypeError, IndexError): return False, "" total_vol = bid_vol + ask_vol diff --git a/backend/engine/mtf_analyzer.py b/backend/engine/mtf_analyzer.py index f475d9bafdf93cb8cb71ed042db8206a8d01fc6a..6658f663d5bddd8bac74dcad4d530403a22e8310 100644 --- a/backend/engine/mtf_analyzer.py +++ b/backend/engine/mtf_analyzer.py @@ -12,16 +12,30 @@ from typing import Any logger = logging.getLogger(__name__) +def _valid_ohlc_candles(candles: list[dict]) -> list[dict]: + """Filter candles to rows that contain non-null high, low, and close values.""" + if not candles: + return [] + return [ + c for c in candles + if isinstance(c, dict) + and c.get("high") is not None + and c.get("low") is not None + and c.get("close") is not None + ] + + def _atr(candles: list[dict], period: int = 14) -> float: """Average True Range over the most recent `period` candles.""" - if len(candles) < 2: + valid = _valid_ohlc_candles(candles) + if len(valid) < 2: return 0.0 - recent = candles[-(period + 1):] + recent = valid[-(period + 1):] trs = [] for i in range(1, len(recent)): - high = recent[i]["high"] - low = recent[i]["low"] - prev_close = recent[i - 1]["close"] + high = float(recent[i]["high"]) + low = float(recent[i]["low"]) + prev_close = float(recent[i - 1]["close"]) tr = max(high - low, abs(high - prev_close), abs(low - prev_close)) trs.append(tr) 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 0.45–0.8 → compressed / ranging (15M sweep) < 0.45 → ultra-low volatility / micro squeeze (5M) """ - if len(candles) < period + 1: + valid = _valid_ohlc_candles(candles) + if len(valid) < period + 1: return 1.0 - current_atr = _atr(candles, period) + current_atr = _atr(valid, period) # Compute rolling ATRs across available candles rolling_atrs = [] - step = max(1, len(candles) // 10) - for start in range(0, len(candles) - period, step): - chunk = candles[start: start + period + 1] + step = max(1, len(valid) // 10) + for start in range(0, len(valid) - period, step): + chunk = valid[start: start + period + 1] a = _atr(chunk, period) if a > 0: rolling_atrs.append(a) @@ -63,12 +78,13 @@ def _calc_atr_stretch(candles: list[dict], ema_period: int = 9, atr_period: int (close - EMA(ema_period)) / ATR(atr_period) Positive = stretched above EMA, Negative = stretched below EMA. """ - if not candles or len(candles) < atr_period + 1: + valid = _valid_ohlc_candles(candles) + if len(valid) < atr_period + 1: return 0.0 - atr_val = _atr(candles, atr_period) + atr_val = _atr(valid, atr_period) if atr_val <= 0: return 0.0 - closes = [float(c["close"]) for c in candles if "close" in c] + closes = [float(c["close"]) for c in valid] if not closes: return 0.0 ema_val = _calc_ema(closes, ema_period) @@ -108,22 +124,23 @@ def _market_structure(candles: list[dict]) -> str: 4. EMA(20) / EMA(9) trend confluence confirmation 5. Mixed / conflicting = 'ranging' """ - if len(candles) < 5: + valid = _valid_ohlc_candles(candles) + if len(valid) < 5: return "ranging" - closes = [c["close"] for c in candles] - highs = [c["high"] for c in candles] - lows = [c["low"] for c in candles] + closes = [float(c["close"]) for c in valid] + highs = [float(c["high"]) for c in valid] + lows = [float(c["low"]) for c in valid] # Find swing highs and swing lows across the last 30 candles - window = min(len(candles), 30) - start_idx = len(candles) - window + window = min(len(valid), 30) + start_idx = len(valid) - window # Pass 1: 5-bar Bill Williams fractals (robust against micro-noise) swing_highs: list[float] = [] swing_lows: list[float] = [] - for i in range(start_idx + 2, len(candles) - 2): + for i in range(start_idx + 2, len(valid) - 2): if (highs[i] >= highs[i - 1] and highs[i] >= highs[i - 2] and highs[i] >= highs[i + 1] and highs[i] >= highs[i + 2]): swing_highs.append(highs[i]) @@ -135,7 +152,7 @@ def _market_structure(candles: list[dict]) -> str: if len(swing_highs) < 2 or len(swing_lows) < 2: swing_highs.clear() swing_lows.clear() - for i in range(start_idx + 1, len(candles) - 1): + for i in range(start_idx + 1, len(valid) - 1): if highs[i] >= highs[i - 1] and highs[i] >= highs[i + 1]: swing_highs.append(highs[i]) if lows[i] <= lows[i - 1] and lows[i] <= lows[i + 1]: diff --git a/backend/engine/outcome_evaluator.py b/backend/engine/outcome_evaluator.py index dff9120869e7f279aaa03df9e194d86b545d257f..efce16424af6ccb68ebdf50d932a4e9461659017 100644 --- a/backend/engine/outcome_evaluator.py +++ b/backend/engine/outcome_evaluator.py @@ -28,7 +28,8 @@ def _to_epoch_ms(val: Any) -> int: if val is None: return 0 if isinstance(val, datetime): - return int(val.timestamp() * 1000) + dt = val if val.tzinfo is not None else val.replace(tzinfo=timezone.utc) + return int(dt.timestamp() * 1000) if isinstance(val, (int, float)): v = float(val) if v >= 100_000_000_000: @@ -37,6 +38,8 @@ def _to_epoch_ms(val: Any) -> int: if isinstance(val, str): try: dt = datetime.fromisoformat(val.replace("Z", "+00:00")) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) return int(dt.timestamp() * 1000) except ValueError: try: @@ -46,6 +49,15 @@ def _to_epoch_ms(val: Any) -> int: return 0 +def _first_float(mapping: dict[str, Any], *keys: str) -> float | None: + """Return the first non-None numeric value across fallback keys.""" + for k in keys: + val = mapping.get(k) + if val is not None: + return float(val) + return None + + def evaluate_prediction_against_candles( pred: dict[str, Any], candles: list[dict[str, Any]], @@ -60,11 +72,13 @@ def evaluate_prediction_against_candles( return None try: - entry = float(pred.get("entry_price", pred.get("entry"))) - sl = float(pred["stop_loss"]) - tp1 = float(pred.get("tp1", pred.get("take_profit_1"))) - tp2 = float(pred.get("tp2", pred.get("take_profit_2"))) - except (KeyError, TypeError, ValueError): + entry = _first_float(pred, "entry_price", "entry") + sl = _first_float(pred, "stop_loss") + tp1 = _first_float(pred, "tp1", "take_profit_1") + tp2 = _first_float(pred, "tp2", "take_profit_2") + if entry is None or sl is None or tp1 is None or tp2 is None: + return None + except (TypeError, ValueError): return None risk = abs(entry - sl) @@ -90,8 +104,10 @@ def evaluate_prediction_against_candles( tp1_hit = False for _, bar in window_bars: - high = float(bar.get("high", 0.0)) - low = float(bar.get("low", 0.0)) + high = float(bar.get("high") or 0.0) + low = float(bar.get("low") or 0.0) + if high <= 0 or low <= 0: + continue if not tp1_hit: if direction == "LONG": @@ -130,7 +146,8 @@ def evaluate_prediction_against_candles( if not window_bars: return None - last_close = float(window_bars[-1][1].get("close", entry)) + valid_closes = [float(b["close"]) for _, b in window_bars if b.get("close") is not None] + last_close = valid_closes[-1] if valid_closes else entry close_r = ((last_close - entry) / risk) if direction == "LONG" else ((entry - last_close) / risk) if tp1_hit: 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: tf = cfg["eval_tf"] limit = int(cfg["limit"]) candles: list[dict[str, Any]] = [] - if binance_client is not None: - try: - candles = await binance_client.fetch_ohlcv(symbol, tf, limit=limit) or [] - except Exception: - candles = [] - if not candles and bybit_client is not None: + for client in (binance_client, bybit_client): + if client is None or candles: + continue + ohlcv_fn = getattr(client, "get_ohlcv", None) or getattr(client, "fetch_ohlcv", None) + if not callable(ohlcv_fn): + continue try: - candles = await bybit_client.fetch_ohlcv(symbol, tf, limit=limit) or [] + candles = await ohlcv_fn(symbol, tf, limit=limit) or [] except Exception: candles = [] if not candles: diff --git a/backend/engine/predictive_engine.py b/backend/engine/predictive_engine.py index 254ad73e84c78cc5e72bb1ccae456f171844b2ad..022f659e6d7eb6e7615a8ee2af6ed88f02fe3232 100644 --- a/backend/engine/predictive_engine.py +++ b/backend/engine/predictive_engine.py @@ -77,8 +77,8 @@ def _compute_liquidation_magnets( "primary_magnet": "UPPER", } - recent_highs = [c["high"] for c in candles if c.get("high", 0) > 0] - recent_lows = [c["low"] for c in candles if c.get("low", 0) > 0] + recent_highs = [c["high"] for c in candles if (c.get("high") or 0) > 0] + recent_lows = [c["low"] for c in candles if (c.get("low") or 0) > 0] if not recent_highs or not recent_lows: upper = mark_price * 1.025 diff --git a/backend/engine/signal_engine.py b/backend/engine/signal_engine.py index 74b9d364f5b35d1f4b8b705cb7b3e257cb400a5e..311b795034c5e6887e7d23d8c69578bfd47f0329 100644 --- a/backend/engine/signal_engine.py +++ b/backend/engine/signal_engine.py @@ -186,10 +186,10 @@ def _is_half_rising(sorted_trades: list[dict], total_cvd: float) -> bool: first, second = _split_trades_by_midpoint(sorted_trades) if not first or not second: return total_cvd > 0 - h1_buy = sum(t.get("qty", 0.0) for t in first if not t.get("is_buyer_maker", False)) - h1_sell = sum(t.get("qty", 0.0) for t in first if t.get("is_buyer_maker", False)) - h2_buy = sum(t.get("qty", 0.0) for t in second if not t.get("is_buyer_maker", False)) - h2_sell = sum(t.get("qty", 0.0) for t in second if t.get("is_buyer_maker", False)) + h1_buy = sum(float(t.get("qty") or 0.0) for t in first if not t.get("is_buyer_maker", False)) + h1_sell = sum(float(t.get("qty") or 0.0) for t in first if t.get("is_buyer_maker", False)) + h2_buy = sum(float(t.get("qty") or 0.0) for t in second if not t.get("is_buyer_maker", False)) + h2_sell = sum(float(t.get("qty") or 0.0) for t in second if t.get("is_buyer_maker", False)) h1_cvd, h2_cvd = h1_buy - h1_sell, h2_buy - h2_sell h1_rat = h1_cvd / (h1_buy + h1_sell) if (h1_buy + h1_sell) > 0 else 0.0 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( } if not spot_trades: - fut_buy = sum(t.get("qty", 0.0) for t in futures_trades if not t.get("is_buyer_maker", False)) - fut_sell = sum(t.get("qty", 0.0) for t in futures_trades if t.get("is_buyer_maker", False)) + fut_buy = sum(float(t.get("qty") or 0.0) for t in futures_trades if not t.get("is_buyer_maker", False)) + fut_sell = sum(float(t.get("qty") or 0.0) for t in futures_trades if t.get("is_buyer_maker", False)) futures_cvd = fut_buy - fut_sell return { "value": f"Perp: {futures_cvd:+.1f} (No Spot)", @@ -326,29 +326,29 @@ def _compute_spot_futures_cvd( } # Sort trades chronologically and intersect overlapping Spot/Futures time window when populated - sorted_spot = sorted(spot_trades, key=lambda t: t.get("time", 0)) - sorted_fut = sorted(futures_trades, key=lambda t: t.get("time", 0)) + sorted_spot = sorted(spot_trades, key=lambda t: float(t.get("time") or 0)) + sorted_fut = sorted(futures_trades, key=lambda t: float(t.get("time") or 0)) - spot_times = [float(t.get("time", 0) or 0) for t in sorted_spot if float(t.get("time", 0) or 0) > 0] - fut_times = [float(t.get("time", 0) or 0) for t in sorted_fut if float(t.get("time", 0) or 0) > 0] + spot_times = [float(t.get("time") or 0) for t in sorted_spot if float(t.get("time") or 0) > 0] + fut_times = [float(t.get("time") or 0) for t in sorted_fut if float(t.get("time") or 0) > 0] if spot_times and fut_times: overlap_start = max(spot_times[0], fut_times[0]) overlap_end = min(spot_times[-1], fut_times[-1]) if overlap_start < overlap_end: - aligned_spot = [t for t in sorted_spot if overlap_start <= float(t.get("time", 0) or 0) <= overlap_end] - aligned_fut = [t for t in sorted_fut if overlap_start <= float(t.get("time", 0) or 0) <= overlap_end] + aligned_spot = [t for t in sorted_spot if overlap_start <= float(t.get("time") or 0) <= overlap_end] + aligned_fut = [t for t in sorted_fut if overlap_start <= float(t.get("time") or 0) <= overlap_end] if len(aligned_spot) >= 5 and len(aligned_fut) >= 5: sorted_spot = aligned_spot sorted_fut = aligned_fut - spot_buy = sum(t.get("qty", 0.0) for t in sorted_spot if not t.get("is_buyer_maker", False)) - spot_sell = sum(t.get("qty", 0.0) for t in sorted_spot if t.get("is_buyer_maker", False)) + spot_buy = sum(float(t.get("qty") or 0.0) for t in sorted_spot if not t.get("is_buyer_maker", False)) + spot_sell = sum(float(t.get("qty") or 0.0) for t in sorted_spot if t.get("is_buyer_maker", False)) spot_total = spot_buy + spot_sell spot_cvd = spot_buy - spot_sell spot_ratio = (spot_cvd / spot_total) if spot_total > 0 else 0.0 - fut_buy = sum(t.get("qty", 0.0) for t in sorted_fut if not t.get("is_buyer_maker", False)) - fut_sell = sum(t.get("qty", 0.0) for t in sorted_fut if t.get("is_buyer_maker", False)) + fut_buy = sum(float(t.get("qty") or 0.0) for t in sorted_fut if not t.get("is_buyer_maker", False)) + fut_sell = sum(float(t.get("qty") or 0.0) for t in sorted_fut if t.get("is_buyer_maker", False)) fut_total = fut_buy + fut_sell futures_cvd = fut_buy - fut_sell fut_ratio = (futures_cvd / fut_total) if fut_total > 0 else 0.0 @@ -495,40 +495,82 @@ def _compute_oi_divergence( ) -> dict[str, Any]: """ Open Interest + Price divergence signal (OI-Weighted across Binance, Bybit, OKX, and Bitget). - - 1. Price↑ + OI↑ (>+0.05%) → Real Long Inflow (+1) - 2. Price↑ + OI↓ (<-0.05%) → Short Covering Exhaustion / Weak Rally (-1) - 3. Price↓ + OI↑ (>+0.05%) → Real Short Inflow (-1) - 4. Price↓ + OI↓ (<-0.05%) → Long Liquidation / Squeeze Exhaustion Done (+1) + Computes both 15m/1h Intraday divergence and 4h Swing divergence. + + 1. Price↑ + OI↑ (>+0.25%) → Real Long Inflow (+1 / +2) + 2. Price↑ + OI↓ (<-0.25%) → Short Covering Exhaustion / Weak Rally (-1) + 3. Price↓ + OI↑ (>+0.25%) → Real Short Inflow (-1 / -2) + 4. Price↓ + OI↓ (<-0.25%) → Long Liquidation / Squeeze Exhaustion Done (+1) 5. Flat / Small changes → Neutral (0) """ price_changes: list[float] = [] price_weights: list[float] = [] + price_4h_changes: list[float] = [] + price_4h_weights: list[float] = [] oi_changes: list[float] = [] oi_weights: list[float] = [] + oi_1h_changes: list[float] = [] + oi_1h_weights: list[float] = [] + oi_4h_changes: list[float] = [] + oi_4h_weights: list[float] = [] for exch in [binance_data, bybit_data, okx_data, bitget_data]: if not exch: continue w = _extract_venue_oi_weight(exch) + ohlcv = exch.get("ohlcv", {}) or {} # 15m candle price change % - candles = exch.get("ohlcv", {}).get("15m", []) - if len(candles) >= 2 and candles[-2]["close"] > 0: - pc = (candles[-1]["close"] - candles[-2]["close"]) / candles[-2]["close"] * 100 + candles = ohlcv.get("15m", []) + if len(candles) >= 2 and (candles[-2].get("close") or 0) > 0 and candles[-1].get("close") is not None: + prev_c = float(candles[-2]["close"]) + curr_c = float(candles[-1]["close"]) + pc = (curr_c - prev_c) / prev_c * 100 price_changes.append(pc) price_weights.append(w) - # OI change % + # 4h candle price change % (or 4-bar 1h fallback) + c4h = ohlcv.get("4h", []) + c1h = ohlcv.get("1h", []) + if len(c4h) >= 2 and (c4h[-2].get("close") or 0) > 0 and c4h[-1].get("close") is not None: + prev4 = float(c4h[-2]["close"]) + curr4 = float(c4h[-1]["close"]) + pc4 = (curr4 - prev4) / prev4 * 100 + price_4h_changes.append(pc4) + price_4h_weights.append(w) + elif len(c1h) >= 5 and (c1h[-5].get("close") or 0) > 0 and c1h[-1].get("close") is not None: + prev4 = float(c1h[-5]["close"]) + curr4 = float(c1h[-1]["close"]) + pc4 = (curr4 - prev4) / prev4 * 100 + price_4h_changes.append(pc4) + price_4h_weights.append(w) + + # OI change % (15m, 1h, 4h) oi_data = exch.get("open_interest_data") - if oi_data and oi_data.get("oi_change_pct") is not None: - oi_changes.append(float(oi_data["oi_change_pct"])) - oi_weights.append(w) + if oi_data: + if oi_data.get("oi_change_pct") is not None: + oi_changes.append(float(oi_data["oi_change_pct"])) + oi_weights.append(w) + if oi_data.get("oi_change_1h_pct") is not None: + oi_1h_changes.append(float(oi_data["oi_change_1h_pct"])) + oi_1h_weights.append(w) + if oi_data.get("oi_change_4h_pct") is not None: + oi_4h_changes.append(float(oi_data["oi_change_4h_pct"])) + oi_4h_weights.append(w) if not price_changes: - return {"value": "No Data", "score": 0, "label": "No Price Data"} + return { + "value": "No Data", + "score": 0, + "intraday_score": 0, + "swing_score": 0, + "label": "No Price Data", + } avg_price_change = _oi_weighted_average(price_changes, price_weights) avg_oi_change = _oi_weighted_average(oi_changes, oi_weights) if oi_changes else 0.0 + avg_oi_1h_change = _oi_weighted_average(oi_1h_changes, oi_1h_weights) if oi_1h_changes else avg_oi_change + avg_oi_4h_change = _oi_weighted_average(oi_4h_changes, oi_4h_weights) if oi_4h_changes else avg_oi_1h_change + avg_price_4h_change = _oi_weighted_average(price_4h_changes, price_4h_weights) if price_4h_changes else avg_price_change # Robust threshold to filter sub-tick micro-noise on 15m timeframe: # Minimum 0.15% price displacement and 0.25% net Open Interest expansion/unwinding @@ -569,11 +611,32 @@ def _compute_oi_divergence( direction_val = "Flat (Neutral)" label = "Balanced Market Flow" + # Swing 4h OI score uses 4h OI expansion (>0.50%) + 4h price displacement (>0.40%) when 4h OI history exists + swing_score = score + if oi_4h_changes: + p4_up = avg_price_4h_change > 0.40 + p4_dn = avg_price_4h_change < -0.40 + oi4_up = avg_oi_4h_change > 0.50 + oi4_dn = avg_oi_4h_change < -0.50 + if p4_up and oi4_up: + swing_score = 1 + elif p4_up and oi4_dn: + swing_score = -1 + elif p4_dn and oi4_up: + swing_score = -1 + elif p4_dn and oi4_dn: + swing_score = 1 + return { "value": direction_val, "price_change_pct": round(avg_price_change, 4), + "price_change_4h_pct": round(avg_price_4h_change, 4), "oi_change_pct": round(avg_oi_change, 4), + "oi_change_1h_pct": round(avg_oi_1h_change, 4), + "oi_change_4h_pct": round(avg_oi_4h_change, 4), "score": score, + "intraday_score": score, + "swing_score": swing_score, "label": label, } @@ -588,12 +651,12 @@ def _compute_cvd(trades: list[dict]) -> dict[str, Any]: return {"value": 0, "delta_ratio": 0.0, "score": 0, "rising": False, "label": "No Trade Data"} # Sort trades chronologically (oldest to newest) to eliminate any exchange discrepancies - sorted_trades = sorted(trades, key=lambda t: t.get("time", 0)) + sorted_trades = sorted(trades, key=lambda t: float(t.get("time") or 0)) buy_vol = 0.0 sell_vol = 0.0 for t in sorted_trades: - qty = t.get("qty", 0.0) + qty = float(t.get("qty") or 0.0) if t.get("is_buyer_maker", False): sell_vol += qty else: @@ -640,12 +703,14 @@ def _compute_cross_exchange( Aligned exchanges confirm price consistency. """ def _pct_change_5m(exch: dict) -> float | None: - candles = exch.get("ohlcv", {}).get("5m", []) + candles = (exch.get("ohlcv") or {}).get("5m", []) if len(candles) < 2: return None - prev = candles[-2]["close"] - curr = candles[-1]["close"] - return (curr - prev) / prev * 100 if prev else None + prev = candles[-2].get("close") + curr = candles[-1].get("close") + if prev is None or curr is None or float(prev) <= 0: + return None + return (float(curr) - float(prev)) / float(prev) * 100 rates = {} if binance_data: @@ -706,32 +771,89 @@ def _compute_ls_ratio( bitget_data: dict | None = None, ) -> dict[str, Any]: """ - Top-trader L/S ratio (OI-Weighted across Binance, Bybit, OKX, and Bitget). + Smart Money Whale Position vs Retail Crowd L/S Ratio + (OI-Weighted across Binance, Bybit, OKX, and Bitget). + Separates Top-Trader Position Size (Smart Money) from Global Account Ratio (Retail Crowd). """ long_ratios: list[float] = [] weights: list[float] = [] + whale_pos_ratios: list[float] = [] + whale_pos_weights: list[float] = [] + retail_ratios: list[float] = [] + retail_weights: list[float] = [] + for exch in [binance_data, bybit_data, okx_data, bitget_data]: if exch and exch.get("ls_ratio_data"): - lr = exch["ls_ratio_data"].get("long_ratio") + ls_d = exch["ls_ratio_data"] + w = _extract_venue_oi_weight(exch) + lr = ls_d.get("long_ratio") if lr is not None: long_ratios.append(float(lr)) - weights.append(_extract_venue_oi_weight(exch)) + weights.append(w) + wp = ls_d.get("top_position_long_ratio") + if wp is not None: + whale_pos_ratios.append(float(wp)) + whale_pos_weights.append(w) + rr = ls_d.get("retail_long_ratio") + if rr is not None: + retail_ratios.append(float(rr)) + retail_weights.append(w) if not long_ratios: - return {"top_trader": None, "retail": None, "score": 0, "label": "No Data"} + return { + "top_trader": None, + "retail": None, + "whale_position_long_ratio": None, + "smart_money_delta": 0.0, + "whale_sentiment": "NEUTRAL", + "score": 0, + "label": "No Data", + } avg_long = _oi_weighted_average(long_ratios, weights) - - if avg_long >= 0.62: - score, label = -1, f"Crowded Retail Longs {avg_long:.1%} → Contrarian Short" - elif avg_long <= 0.38: - score, label = 1, f"Crowded Retail Shorts {avg_long:.1%} → Contrarian Long" + avg_whale_pos = _oi_weighted_average(whale_pos_ratios, whale_pos_weights) if whale_pos_ratios else None + avg_retail = _oi_weighted_average(retail_ratios, retail_weights) if retail_ratios else avg_long + smart_money_delta = (avg_whale_pos - avg_retail) if (avg_whale_pos is not None and avg_retail is not None) else 0.0 + + whale_sentiment = "NEUTRAL" + # Smart Money Whale Position vs Retail Crowd Divergence + if avg_whale_pos is not None and abs(smart_money_delta) >= 0.07: + if smart_money_delta >= 0.12 and avg_whale_pos >= 0.56: + score = 2 + whale_sentiment = "STRONG_WHALE_LONG" + label = f"Whale Position Accumulation ({avg_whale_pos:.1%} Whale Long vs {avg_retail:.1%} Retail) → Strong Smart Money Long" + elif smart_money_delta <= -0.12 and avg_whale_pos <= 0.44: + score = -2 + whale_sentiment = "STRONG_WHALE_SHORT" + label = f"Whale Position Distribution ({1.0 - avg_whale_pos:.1%} Whale Short vs {avg_retail:.1%} Retail Long) → Strong Smart Money Short" + elif smart_money_delta >= 0.07 and avg_whale_pos >= 0.52: + score = 1 + whale_sentiment = "WHALE_LONG_TILT" + label = f"Smart Money Whale Long Tilt ({avg_whale_pos:.1%} Whale Pos vs {avg_retail:.1%} Retail)" + elif smart_money_delta <= -0.07 and avg_whale_pos <= 0.48: + score = -1 + whale_sentiment = "WHALE_SHORT_TILT" + label = f"Smart Money Whale Short Tilt ({1.0 - avg_whale_pos:.1%} Whale Short vs {avg_retail:.1%} Retail)" + elif avg_long >= 0.62: + score, label = -1, f"Crowded Retail Longs {avg_long:.1%} → Contrarian Short" + elif avg_long <= 0.38: + score, label = 1, f"Crowded Retail Shorts {avg_long:.1%} → Contrarian Long" + else: + score, label = 0, f"Balanced L/S {avg_long:.1%}" else: - score, label = 0, f"Balanced L/S {avg_long:.1%}" + if avg_long >= 0.62: + score, label = -1, f"Crowded Retail Longs {avg_long:.1%} → Contrarian Short" + elif avg_long <= 0.38: + score, label = 1, f"Crowded Retail Shorts {avg_long:.1%} → Contrarian Long" + else: + score, label = 0, f"Balanced L/S {avg_long:.1%}" return { "top_trader": round(avg_long, 4), - "retail": None, + "retail": round(avg_retail, 4) if retail_ratios else None, + "whale_position_long_ratio": round(avg_whale_pos, 4) if avg_whale_pos is not None else None, + "smart_money_delta": round(smart_money_delta, 4), + "whale_sentiment": whale_sentiment, "score": score, "label": label, } @@ -846,7 +968,7 @@ def _compute_trade_plan( entry_high = mark_price + (0.05 * atr) # Structure-Based Invalidation Stop Loss: anchor to recent swing low if within [sl_min_pct, sl_max_pct] - recent_lows = [c["low"] for c in ohlcv_1h[-20:] if c.get("low", 0) > 0] if ohlcv_1h else [] + recent_lows = [c["low"] for c in ohlcv_1h[-20:] if (c.get("low") or 0) > 0] if ohlcv_1h else [] if recent_lows: struct_low = min(recent_lows) - (0.2 * atr) if mark_price * long_struct_min <= struct_low <= mark_price * long_struct_max: @@ -902,7 +1024,7 @@ def _compute_trade_plan( entry_high = mark_price + (0.35 * atr) # Structure-Based Invalidation Stop Loss: anchor to recent swing high if within [sl_min_pct, sl_max_pct] - recent_highs = [c["high"] for c in ohlcv_1h[-20:] if c.get("high", 0) > 0] if ohlcv_1h else [] + recent_highs = [c["high"] for c in ohlcv_1h[-20:] if (c.get("high") or 0) > 0] if ohlcv_1h else [] if recent_highs: struct_high = max(recent_highs) + (0.2 * atr) 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 } -def _compute_whale_order_flow(trades: list[dict], mark_price: float) -> dict[str, Any]: +def _compute_whale_order_flow( + trades: list[dict], + mark_price: float, + merged_ohlcv: dict | None = None, + oi_signal: dict | None = None, + ls_signal: dict | None = None, +) -> dict[str, Any]: """ - Institutional Order Flow & Whale Block Trades Analysis. - Analyzes aggressive market taker buy/sell volume and large block orders. + Multi-Layer Institutional Order Flow & True Whale Movement Intelligence: + 1. Dynamic Quantile Block Trade Detection (p95 / median + 1.5% vol floor $5k) + 2. Reconstructed Market Sweep Clustering (coalesces split resting fills sharing exact tick timestamp) + 3. Multi-Candle Whale TWAP Accumulation/Distribution via Klines `taker_buy_volume` (15m / 1h) + 4. Hyperliquid On-Chain Single-Wallet Whale Accumulation Tracker (`taker_wallet` grouping) + 5. Passive Whale Iceberg Limit Absorption Detector (High Taker Sell + Price Hold + OI Expansion) """ - if not trades or mark_price <= 0: - return { - "taker_buy_vol_usd": 0.0, - "taker_sell_vol_usd": 0.0, - "total_vol_usd": 0.0, - "taker_buy_pct": 50.0, - "taker_ratio": 1.0, - "whale_buy_count": 0, - "whale_sell_count": 0, - "whale_buy_vol_usd": 0.0, - "whale_sell_vol_usd": 0.0, - "largest_trade_usd": 0.0, - "largest_trade_side": "NONE", - "dynamic_threshold_usd": 5000.0, - "net_whale_threshold_usd": 5000.0, - "flow_verdict": "Order Flow Agregat Seimbang (Belum Ada Data Trades)", - } + # Compute multi-candle TWAP & Iceberg Absorption from OHLCV even when live trade tape is empty + twap_buy_usd = 0.0 + twap_sell_usd = 0.0 + twap_bias = "NEUTRAL" + twap_score = 0 + absorption_type: str | None = None + absorption_note: str | None = None + absorption_score = 0 + + oi_val = (oi_signal or {}).get("oi_change_pct") + oi_chg = float(oi_val) if oi_val is not None else 0.0 + oi_1h_val = (oi_signal or {}).get("oi_change_1h_pct") + oi_1h_chg = float(oi_1h_val) if oi_1h_val is not None else oi_chg + # Only elevate 1H OI over 15m when aligned in sign (or 15m is flat 0.0); never let stale 1H mask active 15m unwinding + if oi_chg != 0.0 and (oi_chg * oi_1h_chg) < 0: + eff_oi_chg = oi_chg + else: + eff_oi_chg = oi_1h_chg if abs(oi_1h_chg) > abs(oi_chg) else oi_chg + + if merged_ohlcv and mark_price > 0: + ref_bars = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or [])[-4:] + 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] + if tb_bars: + for b in tb_bars: + v_tot = float(b.get("volume", 0.0) or 0.0) + v_buy = min(v_tot, max(0.0, float(b.get("taker_buy_volume", 0.0) or 0.0))) + v_sell = max(0.0, v_tot - v_buy) + px_b = float(b.get("close") or mark_price) + twap_buy_usd += v_buy * px_b + twap_sell_usd += v_sell * px_b + + twap_tot_usd = twap_buy_usd + twap_sell_usd + twap_delta_usd = twap_buy_usd - twap_sell_usd + twap_delta_ratio = (twap_delta_usd / twap_tot_usd) if twap_tot_usd > 0 else 0.0 + + # Require institutional notional size (>= $25,000) to classify TWAP accumulation + if twap_tot_usd >= 25_000.0: + if twap_delta_ratio >= 0.06 and eff_oi_chg >= 0.20: + twap_bias = "WHALE_TWAP_LONG_BUILDUP" + twap_score = 2 if (twap_delta_ratio >= 0.12 and eff_oi_chg >= 0.50) else 1 + elif twap_delta_ratio <= -0.06 and eff_oi_chg >= 0.20: + twap_bias = "WHALE_TWAP_SHORT_BUILDUP" + twap_score = -2 if (twap_delta_ratio <= -0.12 and eff_oi_chg >= 0.50) else -1 + elif twap_delta_ratio >= 0.08: + twap_bias = "TWAP_BUY_ACCUMULATION" + twap_score = 1 + elif twap_delta_ratio <= -0.08: + twap_bias = "TWAP_SELL_DISTRIBUTION" + twap_score = -1 + + # Iceberg Limit Absorption on latest completed/active 15m or 1h bar + if ref_bars: + last_b = ref_bars[-1] + b_high = float(last_b.get("high", 0.0) or 0.0) + b_low = float(last_b.get("low", 0.0) or 0.0) + b_close = float(last_b.get("close", 0.0) or 0.0) + b_rng = b_high - b_low + min_meaningful_rng = b_close * 0.001 if b_close > 0 else 0.0 + close_pos = ((b_close - b_low) / b_rng) if (b_rng > 0 and b_rng >= min_meaningful_rng) else 0.5 + if b_rng >= min_meaningful_rng and twap_tot_usd >= 25_000.0 and eff_oi_chg >= 0.25: + if twap_delta_ratio <= -0.05 and close_pos >= 0.60: + absorption_type = "BULLISH_ICEBERG_ABSORPTION" + absorption_note = f"Limit Bid Iceberg menyerap jualan agresif + OI naik {eff_oi_chg:+.2f}%" + absorption_score = 1 + elif twap_delta_ratio >= 0.05 and close_pos <= 0.40: + absorption_type = "BEARISH_ICEBERG_ABSORPTION" + absorption_note = f"Limit Ask Iceberg menahan beli agresif + OI naik {eff_oi_chg:+.2f}%" + absorption_score = -1 + else: + twap_delta_usd = 0.0 + twap_delta_ratio = 0.0 + + sm_delta = float((ls_signal or {}).get("smart_money_delta", 0.0) or 0.0) + whale_pos_lr = (ls_signal or {}).get("whale_position_long_ratio") + retail_acc_lr = (ls_signal or {}).get("retail") taker_buy_vol = 0.0 taker_sell_vol = 0.0 parsed_trades = [] + # Sweep reconstruction: coalesce split fills sharing exact positive (venue, time, is_sell_taker) + sweep_buckets: dict[tuple[str, int, bool], float] = {} + unbucketed_sweeps: list[tuple[float, bool]] = [] + # Hyperliquid on-chain wallet tracker: {wallet: [buy_usd, sell_usd]} + wallet_flows: dict[str, list[float]] = {} + + if trades and mark_price > 0: + for t in trades: + try: + px = float(t.get("price", 0.0)) + qty = float(t.get("qty", 0.0)) + if px <= 0 or qty <= 0: + continue + usd_val = px * qty + is_sell_taker = bool(t.get("is_buyer_maker", False)) + parsed_trades.append((usd_val, is_sell_taker)) + if is_sell_taker: + taker_sell_vol += usd_val + else: + taker_buy_vol += usd_val - for t in trades: - try: - px = float(t.get("price", 0.0)) - qty = float(t.get("qty", 0.0)) - if px <= 0 or qty <= 0: + t_ms = int(t.get("time", 0) or 0) + venue = str(t.get("venue", "default")) + if t_ms > 0: + b_key = (venue, t_ms, is_sell_taker) + sweep_buckets[b_key] = sweep_buckets.get(b_key, 0.0) + usd_val + else: + unbucketed_sweeps.append((usd_val, is_sell_taker)) + + w_addr = t.get("taker_wallet") + if w_addr and isinstance(w_addr, str): + wf = wallet_flows.setdefault(w_addr, [0.0, 0.0]) + if is_sell_taker: + wf[1] += usd_val + else: + wf[0] += usd_val + except Exception: continue - usd_val = px * qty - is_sell_taker = bool(t.get("is_buyer_maker", False)) - parsed_trades.append((usd_val, is_sell_taker)) - if is_sell_taker: - taker_sell_vol += usd_val - else: - taker_buy_vol += usd_val - except Exception: - continue + + # Neutralize absorbed aggressive TWAP flow when opposite Limit Iceberg absorption confirms + eff_twap_score = 0 if (absorption_score * twap_score < 0) else twap_score if not parsed_trades: + fallback_buy_pct = ( + round(twap_buy_usd / (twap_buy_usd + twap_sell_usd) * 100.0, 1) + if (twap_buy_usd + twap_sell_usd) > 0 + else 50.0 + ) + fallback_ratio = ( + round(twap_buy_usd / twap_sell_usd, 2) + if twap_sell_usd > 0 + else (99.0 if twap_buy_usd > 0 else 1.0) + ) + comp_score = max(-2, min(2, eff_twap_score + absorption_score)) + if absorption_type == "BULLISH_ICEBERG_ABSORPTION" and comp_score >= 0: + verdict = f"🛡️ Iceberg Absorption Paus (Bullish): {absorption_note}" + elif absorption_type == "BEARISH_ICEBERG_ABSORPTION" and comp_score <= 0: + verdict = f"🛡️ Iceberg Absorption Paus (Bearish): {absorption_note}" + elif twap_bias == "WHALE_TWAP_LONG_BUILDUP": + verdict = f"Akumulasi TWAP Paus (Klines): Net Taker Buy +${twap_delta_usd:,.0f} disertai ekspansi OI {eff_oi_chg:+.2f}%." + elif twap_bias == "WHALE_TWAP_SHORT_BUILDUP": + verdict = f"Distribusi TWAP Paus (Klines): Net Taker Sell -${abs(twap_delta_usd):,.0f} disertai ekspansi OI {eff_oi_chg:+.2f}%." + elif twap_bias == "TWAP_BUY_ACCUMULATION": + verdict = f"Akumulasi TWAP Beli (Klines): Net Taker Buy +${twap_delta_usd:,.0f}." + elif twap_bias == "TWAP_SELL_DISTRIBUTION": + verdict = f"Distribusi TWAP Jual (Klines): Net Taker Sell -${abs(twap_delta_usd):,.0f}." + else: + verdict = ( + "Order Flow Agregat Seimbang (Belum Ada Data Trades)" + if not trades + else "Order Flow Agregat Seimbang" + ) return { - "taker_buy_vol_usd": 0.0, - "taker_sell_vol_usd": 0.0, - "total_vol_usd": 0.0, - "taker_buy_pct": 50.0, - "taker_ratio": 1.0, + "taker_buy_vol_usd": round(twap_buy_usd, 2), + "taker_sell_vol_usd": round(twap_sell_usd, 2), + "total_vol_usd": round(twap_buy_usd + twap_sell_usd, 2), + "taker_buy_pct": fallback_buy_pct, + "taker_ratio": fallback_ratio, "whale_buy_count": 0, "whale_sell_count": 0, "whale_buy_vol_usd": 0.0, @@ -1289,7 +1533,28 @@ def _compute_whale_order_flow(trades: list[dict], mark_price: float) -> dict[str "largest_trade_side": "NONE", "dynamic_threshold_usd": 5000.0, "net_whale_threshold_usd": 5000.0, - "flow_verdict": "Order Flow Agregat Seimbang", + "sweep_buy_count": 0, + "sweep_sell_count": 0, + "sweep_buy_vol_usd": 0.0, + "sweep_sell_vol_usd": 0.0, + "largest_sweep_usd": 0.0, + "twap_bias": twap_bias, + "twap_buy_pct": round(50.0 + twap_delta_ratio * 50.0, 1), + "twap_net_delta_usd": round(twap_delta_usd, 2), + "twap_delta_ratio": round(twap_delta_ratio, 4), + "absorption_type": absorption_type, + "absorption_note": absorption_note, + "is_iceberg_absorbing": absorption_score != 0, + "onchain_whale_wallets": 0, + "onchain_buy_vol_usd": 0.0, + "onchain_sell_vol_usd": 0.0, + "top_whale_wallet_usd": 0.0, + "top_whale_wallet_side": "NONE", + "whale_position_long_ratio": whale_pos_lr, + "retail_account_long_ratio": retail_acc_lr, + "smart_money_delta": sm_delta, + "whale_composite_score": comp_score, + "flow_verdict": verdict, } 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 whale_buy_vol = sum(whale_buys) whale_sell_vol = sum(whale_sells) + # Reconstructed sweep orders (coalesces split fills at identical tick timestamp) + all_sweeps = [(val, is_sell) for (_, _, is_sell), val in sweep_buckets.items()] + unbucketed_sweeps + sweep_buys = [v for v, is_sell in all_sweeps if (not is_sell) and v >= threshold] + sweep_sells = [v for v, is_sell in all_sweeps if is_sell and v >= threshold] + sweep_buy_vol = sum(sweep_buys) + sweep_sell_vol = sum(sweep_sells) + largest_sweep_usd = max((v for v, _ in all_sweeps), default=0.0) + + # Hyperliquid On-Chain Single-Wallet Whale Accumulation + onchain_whale_wallets = 0 + onchain_buy_vol_usd = 0.0 + onchain_sell_vol_usd = 0.0 + top_whale_wallet_usd = 0.0 + top_whale_wallet_side = "NONE" + for w_buy_u, w_sell_u in wallet_flows.values(): + net_w = w_buy_u - w_sell_u + if abs(net_w) >= max(10_000.0, threshold): + onchain_whale_wallets += 1 + if net_w > 0: + onchain_buy_vol_usd += net_w + else: + onchain_sell_vol_usd += abs(net_w) + if abs(net_w) > top_whale_wallet_usd: + top_whale_wallet_usd = abs(net_w) + top_whale_wallet_side = "BUY" if net_w > 0 else "SELL" + + onchain_score = 0 + if onchain_buy_vol_usd > onchain_sell_vol_usd * 1.4 and onchain_buy_vol_usd >= threshold: + onchain_score = 1 + elif onchain_sell_vol_usd > onchain_buy_vol_usd * 1.4 and onchain_sell_vol_usd >= threshold: + onchain_score = -1 + + # Also check live tape Iceberg Absorption if not already triggered by klines + if absorption_score == 0 and merged_ohlcv and total_vol >= 25_000.0 and eff_oi_chg >= 0.25: + ref_b = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or []) + if ref_b: + lb = ref_b[-1] + l_high = float(lb.get("high", 0.0) or 0.0) + l_low = float(lb.get("low", 0.0) or 0.0) + l_close = float(lb.get("close", 0.0) or 0.0) + rng = l_high - l_low + min_rng = l_close * 0.001 if l_close > 0 else 0.0 + c_pos = ((l_close - l_low) / rng) if (rng > 0 and rng >= min_rng) else 0.5 + if rng >= min_rng and buy_pct <= 40.0 and c_pos >= 0.60: + absorption_type = "BULLISH_ICEBERG_ABSORPTION" + absorption_note = f"Jualan agresif ({100.0 - buy_pct:.0f}% Taker Sell) diserap Limit Buy Wall + OI naik {eff_oi_chg:+.2f}%" + absorption_score = 1 + elif buy_pct >= 60.0 and c_pos <= 0.40: + absorption_type = "BEARISH_ICEBERG_ABSORPTION" + absorption_note = f"Beli agresif ({buy_pct:.0f}% Taker Buy) ditahan Limit Sell Wall + OI naik {eff_oi_chg:+.2f}%" + absorption_score = -1 + + # Composite Whale Score [-2, +2] + eff_whale_buy = max(whale_buy_vol, sweep_buy_vol) + eff_whale_sell = max(whale_sell_vol, sweep_sell_vol) + block_score = 0 + if eff_whale_buy > eff_whale_sell * 1.4 and eff_whale_buy >= threshold: + block_score = 2 if eff_whale_buy >= threshold * 3.0 and len(sweep_buys) >= 2 else 1 + elif eff_whale_sell > eff_whale_buy * 1.4 and eff_whale_sell >= threshold: + block_score = -2 if eff_whale_sell >= threshold * 3.0 and len(sweep_sells) >= 2 else -1 + + # Neutralize absorbed aggressive block/TWAP flow when passive Iceberg absorption confirms + eff_block_score = 0 if (absorption_score * block_score < 0) else block_score + eff_twap_score_main = 0 if (absorption_score * twap_score < 0) else twap_score + whale_composite_score = max( + -2, + min(2, eff_block_score + eff_twap_score_main + absorption_score + onchain_score), + ) + largest_val, largest_is_sell = max(parsed_trades, key=lambda x: x[0]) largest_side = "SELL" if largest_is_sell else "BUY" - if len(whale_buys) > 0 and len(whale_sells) == 0: + if absorption_type == "BULLISH_ICEBERG_ABSORPTION" and whale_composite_score >= 0: + verdict = f"🛡️ Iceberg Absorption Paus (Bullish): Jualan agresif diserap Limit Buy Wall + OI naik {eff_oi_chg:+.2f}%!" + elif absorption_type == "BEARISH_ICEBERG_ABSORPTION" and whale_composite_score <= 0: + verdict = f"🛡️ Iceberg Absorption Paus (Bearish): Beli agresif ditahan Limit Sell Wall + OI naik {eff_oi_chg:+.2f}%!" + elif len(whale_buys) > 0 and len(whale_sells) == 0: verdict = f"Paus Agresif Sisi Beli: {len(whale_buys)} block buy (${whale_buy_vol:,.0f}) tanpa block sell tandingan!" elif len(whale_sells) > 0 and len(whale_buys) == 0: verdict = f"Paus Agresif Sisi Jual: {len(whale_sells)} block sell (${whale_sell_vol:,.0f}) tanpa block buy tandingan!" - elif whale_buy_vol > whale_sell_vol * 1.5: - 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)." - elif whale_sell_vol > whale_buy_vol * 1.5: - 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)." + elif eff_whale_buy > eff_whale_sell * 1.5 and eff_whale_buy >= threshold: + 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}." + elif eff_whale_sell > eff_whale_buy * 1.5 and eff_whale_sell >= threshold: + 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}." + elif twap_bias == "WHALE_TWAP_LONG_BUILDUP": + verdict = f"Akumulasi TWAP Paus: Net Taker Buy +${twap_delta_usd:,.0f} + OI naik {eff_oi_chg:+.2f}%." + elif twap_bias == "WHALE_TWAP_SHORT_BUILDUP": + verdict = f"Distribusi TWAP Paus: Net Taker Sell -${abs(twap_delta_usd):,.0f} + OI naik {eff_oi_chg:+.2f}%." + elif twap_bias == "TWAP_BUY_ACCUMULATION": + verdict = f"Akumulasi TWAP Beli: Net Taker Buy +${twap_delta_usd:,.0f} ({50.0 + twap_delta_ratio * 50.0:.1f}% Taker Buy)." + elif twap_bias == "TWAP_SELL_DISTRIBUTION": + verdict = f"Distribusi TWAP Jual: Net Taker Sell -${abs(twap_delta_usd):,.0f} ({50.0 - twap_delta_ratio * 50.0:.1f}% Taker Sell)." elif buy_pct >= 58.0: verdict = f"Taker Buy Dominan: {buy_pct:.1f}% volume taker agresif beli (Rasio {taker_ratio:.2f}x)." elif buy_pct <= 42.0: @@ -1354,6 +1700,27 @@ def _compute_whale_order_flow(trades: list[dict], mark_price: float) -> dict[str "largest_trade_side": largest_side, "dynamic_threshold_usd": round(threshold, 2), "net_whale_threshold_usd": round(net_whale_threshold, 2), + "sweep_buy_count": len(sweep_buys), + "sweep_sell_count": len(sweep_sells), + "sweep_buy_vol_usd": round(sweep_buy_vol, 2), + "sweep_sell_vol_usd": round(sweep_sell_vol, 2), + "largest_sweep_usd": round(largest_sweep_usd, 2), + "twap_bias": twap_bias, + "twap_buy_pct": round(50.0 + twap_delta_ratio * 50.0, 1), + "twap_net_delta_usd": round(twap_delta_usd, 2), + "twap_delta_ratio": round(twap_delta_ratio, 4), + "absorption_type": absorption_type, + "absorption_note": absorption_note, + "is_iceberg_absorbing": absorption_score != 0, + "onchain_whale_wallets": onchain_whale_wallets, + "onchain_buy_vol_usd": round(onchain_buy_vol_usd, 2), + "onchain_sell_vol_usd": round(onchain_sell_vol_usd, 2), + "top_whale_wallet_usd": round(top_whale_wallet_usd, 2), + "top_whale_wallet_side": top_whale_wallet_side, + "whale_position_long_ratio": whale_pos_lr, + "retail_account_long_ratio": retail_acc_lr, + "smart_money_delta": sm_delta, + "whale_composite_score": whale_composite_score, "flow_verdict": verdict, } @@ -1686,19 +2053,21 @@ class SignalEngine: hl_mark_px = hyperliquid.get("mark_price") if hyperliquid else None ref_mark_px = binance_mark or bybit_mark or bitget_mark or okx_mark or hl_mark_px or 0.0 - # CVD & Whale Order Flow: combine Binance, Bybit, OKX, and Bitget (normalized to canonical contract scale). + # CVD & Whale Order Flow: combine Binance, Bybit, OKX, Bitget, and Hyperliquid (normalized to canonical contract scale). trades = [] - for v_data, v_mark in [ - (binance, binance_mark), - (bybit, bybit_mark), - (okx, okx_mark), - (bitget, bitget_mark), + for v_name, v_data, v_mark in [ + ("binance", binance, binance_mark), + ("bybit", bybit, bybit_mark), + ("okx", okx, okx_mark), + ("bitget", bitget, bitget_mark), + ("hyperliquid", hyperliquid, hl_mark_px), ]: if v_data and v_data.get("trades"): v_trades = v_data["trades"] sample_px = v_mark or (v_trades[0].get("price") if v_trades else None) t_scale = _get_multiplier_scale(sample_px, ref_mark_px) - trades.extend(_normalize_trades_scale(v_trades, t_scale)) + for nt in _normalize_trades_scale(v_trades, t_scale): + trades.append({**nt, "venue": v_name}) cvd_signal = _compute_cvd(trades) @@ -1724,15 +2093,60 @@ class SignalEngine: merged_ohlcv[tf] = candles mtf_result = mtf_analyzer.analyze(merged_ohlcv) - if horizon_thresholds is not None and not trades: + if not trades: ref_cvd_bars = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or [])[-10:] - if ref_cvd_bars: - net_delta = sum( - ((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)) - * float(b.get("volume", 0.0) or 1.0) - for b in ref_cvd_bars - ) - tot_vol = sum(float(b.get("volume", 0.0) or 1.0) for b in ref_cvd_bars) + tb_cvd_bars = [ + b for b in ref_cvd_bars + if b.get("taker_buy_volume") is not None and float(b.get("volume", 0.0) or 0.0) > 0 + ] + if tb_cvd_bars: + net_delta = 0.0 + tot_vol = 0.0 + for b in tb_cvd_bars: + v_tot = float(b.get("volume", 0.0) or 0.0) + v_buy = max(0.0, min(v_tot, float(b.get("taker_buy_volume") or 0.0))) + net_delta += (2.0 * v_buy) - v_tot + tot_vol += v_tot + if tot_vol > 0: + ratio = net_delta / tot_vol + buy_pct = 50.0 + ratio * 50.0 + if ratio > 0.06: + cvd_signal = { + **cvd_signal, + "score": 1, + "rising": True, + "value": round(net_delta, 2), + "label": f"Klines Taker CVD Bullish ({buy_pct:.1f}% Buy)", + } + elif ratio < -0.06: + cvd_signal = { + **cvd_signal, + "score": -1, + "rising": False, + "value": round(net_delta, 2), + "label": f"Klines Taker CVD Bearish ({buy_pct:.1f}% Buy)", + } + elif horizon_thresholds is not None and ref_cvd_bars: + net_delta = 0.0 + tot_vol = 0.0 + for b in ref_cvd_bars: + if not isinstance(b, dict): + continue + o = b.get("open") + h = b.get("high") + l_val = b.get("low") + c = b.get("close") + v = b.get("volume") + if None in (o, h, l_val, c): + continue + try: + o_f, h_f, l_f, c_f = float(o), float(h), float(l_val), float(c) + v_f = float(v) if v is not None else 0.0 + except (TypeError, ValueError): + continue + rng = max(h_f - l_f, 1e-9) + net_delta += ((c_f - o_f) / rng) * v_f + tot_vol += v_f if tot_vol > 0: ratio = net_delta / tot_vol if ratio > 0.15: @@ -1856,25 +2270,42 @@ class SignalEngine: ) if mark_price <= 0 and merged_ohlcv: for tf in ["15m", "1h", "5m"]: - if tf in merged_ohlcv and merged_ohlcv[tf]: - candidate_px = merged_ohlcv[tf][-1].get("close", 0.0) + bars = merged_ohlcv.get(tf) or [] + for bar in reversed(bars): + raw_px = bar.get("close") if isinstance(bar, dict) else None + if raw_px is None: + continue + try: + candidate_px = float(raw_px) + except (TypeError, ValueError): + continue if candidate_px > 0: mark_price = candidate_px break + if mark_price > 0: + break # Compute Orderbook Resting Skew & Whale Block Order Flow for Confluence Scoring ob_skew = _compute_orderbook_skew(orderbook, mark_price) - whale_flow_data = _compute_whale_order_flow(trades, mark_price) + whale_flow_data = _compute_whale_order_flow( + trades, + mark_price, + merged_ohlcv=merged_ohlcv, + oi_signal=oi_signal, + ls_signal=ls_signal, + ) - whale_score = 0 + raw_whale_comp = whale_flow_data.get("whale_composite_score") + whale_score = int(raw_whale_comp or 0) w_buy = whale_flow_data.get("whale_buy_vol_usd", 0.0) w_sell = whale_flow_data.get("whale_sell_vol_usd", 0.0) t_buy_pct = whale_flow_data.get("taker_buy_pct", 50.0) dyn_whale_thresh = float(whale_flow_data.get("dynamic_threshold_usd", 25000.0) or 25000.0) - if w_buy > w_sell * 1.4 and w_buy >= dyn_whale_thresh: - whale_score = 1 - elif w_sell > w_buy * 1.4 and w_sell >= dyn_whale_thresh: - whale_score = -1 + if raw_whale_comp is None: + if w_buy > w_sell * 1.4 and w_buy >= dyn_whale_thresh: + whale_score = 1 + elif w_sell > w_buy * 1.4 and w_sell >= dyn_whale_thresh: + whale_score = -1 whale_factor = { "score": whale_score, @@ -1883,6 +2314,20 @@ class SignalEngine: "taker_ratio": whale_flow_data.get("taker_ratio", 1.0), "whale_buy_vol_usd": w_buy, "whale_sell_vol_usd": w_sell, + "sweep_buy_vol_usd": whale_flow_data.get("sweep_buy_vol_usd", 0.0), + "sweep_sell_vol_usd": whale_flow_data.get("sweep_sell_vol_usd", 0.0), + "sweep_buy_count": whale_flow_data.get("sweep_buy_count", 0), + "sweep_sell_count": whale_flow_data.get("sweep_sell_count", 0), + "twap_bias": whale_flow_data.get("twap_bias", "NEUTRAL"), + "twap_buy_pct": whale_flow_data.get("twap_buy_pct", 50.0), + "absorption_type": whale_flow_data.get("absorption_type"), + "absorption_note": whale_flow_data.get("absorption_note"), + "whale_position_long_ratio": whale_flow_data.get("whale_position_long_ratio"), + "retail_account_long_ratio": whale_flow_data.get("retail_account_long_ratio"), + "smart_money_delta": whale_flow_data.get("smart_money_delta"), + "onchain_whale_wallets": whale_flow_data.get("onchain_whale_wallets", 0), + "onchain_buy_vol_usd": whale_flow_data.get("onchain_buy_vol_usd", 0.0), + "onchain_sell_vol_usd": whale_flow_data.get("onchain_sell_vol_usd", 0.0), } ob_factor = { @@ -1913,15 +2358,37 @@ class SignalEngine: regime_name = mtf_result.get("regime", mtf_result.get("market_condition", "trending")) h_thresh_map = horizon_thresholds or {} - factors_primary = dict(factors) - factors_intraday = { + def _apply_contextual_contrarian_gating(h_factors: dict[str, Any]) -> dict[str, Any]: + """Neutralize mild (-1/+1) contrarian funding/basis drag when strong MTF structure AND institutional flow confirm a fresh trend.""" + ms_sc = int(h_factors.get("market_structure", {}).get("score", 0) or 0) + sf_sc = int(h_factors.get("spot_futures_cvd", {}).get("score", 0) or 0) + wh_sc = int(h_factors.get("whale_order_flow", {}).get("score", 0) or 0) + fr_sc = int(h_factors.get("funding_rate", {}).get("score", 0) or 0) + bs_sc = int(h_factors.get("basis", {}).get("score", 0) or 0) + out = dict(h_factors) + if ms_sc >= 2 and (sf_sc >= 1 or wh_sc >= 1): + if fr_sc == -1: + out["funding_rate"] = {**h_factors["funding_rate"], "score": 0} + if bs_sc == -1: + out["basis"] = {**h_factors["basis"], "score": 0} + elif ms_sc <= -2 and (sf_sc <= -1 or wh_sc <= -1): + if fr_sc == 1: + out["funding_rate"] = {**h_factors["funding_rate"], "score": 0} + if bs_sc == 1: + out["basis"] = {**h_factors["basis"], "score": 0} + return out + + factors_primary = _apply_contextual_contrarian_gating(dict(factors)) + factors_intraday = _apply_contextual_contrarian_gating({ **factors, + "oi_divergence": {**oi_signal, "score": oi_signal.get("intraday_score", oi_signal["score"])}, "market_structure": {**ms_signal, "score": mtf_result.get("intraday_structure", ms_signal["score"])}, - } - factors_swing = { + }) + factors_swing = _apply_contextual_contrarian_gating({ **factors, + "oi_divergence": {**oi_signal, "score": oi_signal.get("swing_score", oi_signal["score"])}, "market_structure": {**ms_signal, "score": mtf_result.get("swing_structure", ms_signal["score"])}, - } + }) primary_conf = confluence_scorer.compute( factors_primary, @@ -2118,11 +2585,12 @@ class SignalEngine: avg_fr_val = float(funding_signal["value"]) * 100.0 avg_fr_val = avg_fr_val or 0.0 - # Candidate direction before global circuit breakers (including any intraday chased direction) + swing_chased_dir = swing_raw_dir if (swing_ac["blocked"] and swing_raw_dir in ("LONG", "SHORT")) else None + # Candidate direction before global circuit breakers (including any chased direction) candidate_dir = ( confluence["direction"] if confluence["direction"] in ("LONG", "SHORT") - else (intra_chased_dir or primary_conf["direction"]) + else (intra_chased_dir or swing_chased_dir or primary_conf["direction"]) ) crowded_long_veto = candidate_dir == "LONG" and avg_fr_val > 0.05 @@ -2214,11 +2682,12 @@ class SignalEngine: sniper_grade = "WAIT" elif intra_dir in ("LONG", "SHORT") and sw_dir == intra_dir: sf_aligned = (intra_dir == "LONG" and sf_score > 0) or (intra_dir == "SHORT" and sf_score < 0) + whale_aligned = (intra_dir == "LONG" and whale_score > 0) or (intra_dir == "SHORT" and whale_score < 0) cvd_sc = int(cvd_signal.get("score", 0) or 0) ohlcv_cvd_aligned = bool(horizon_thresholds) and ( (intra_dir == "LONG" and cvd_sc > 0) or (intra_dir == "SHORT" and cvd_sc < 0) ) - if squeeze_active or sf_aligned or ohlcv_cvd_aligned: + if squeeze_active or sf_aligned or whale_aligned or ohlcv_cvd_aligned: sniper_grade = "SNIPER_A_PLUS" else: sniper_grade = "INTRADAY_ONLY" @@ -2293,8 +2762,14 @@ class SignalEngine: extremes_data=extremes_data, ) - if confluence["direction"] == "NEUTRAL" and breakout_radar_data.get("is_breakout_primed"): - if plan.get("action") == "WAIT": + if ( + confluence["direction"] == "NEUTRAL" + and canonical_veto is None + and not is_fake_flag + and liquidity_guard.get("passed", True) + and breakout_radar_data.get("is_breakout_primed") + ): + if plan.get("action") in ("WAIT", "DO NOT TRADE / WAIT"): plan["action"] = "WATCH BREAKOUT" if plan.get("quick_verdict"): plan["quick_verdict"] = f"{breakout_radar_data['radar_label']}: {breakout_radar_data['catalyst_summary']}" diff --git a/backend/engine/symbol_resolver.py b/backend/engine/symbol_resolver.py index 96baa956e0c3749f0dcc5286414a5b69a7b5aab1..33b7c012b89c8104136a0948e6fca3b25ee94a52 100644 --- a/backend/engine/symbol_resolver.py +++ b/backend/engine/symbol_resolver.py @@ -7,24 +7,43 @@ across Binance, Bybit, OKX, and Hyperliquid. import re +# Known meme assets where uppercase 'K' denotes a 1000x contract prefix (e.g. Hyperliquid kPEPE -> KPEPE) +_KNOWN_K_MULTIPLIER_BASES = frozenset({"PEPE", "SHIB", "BONK", "FLOKI", "LUNC", "NEIRO", "DOGS"}) + + +def _strip_multiplier_from_base(raw_base: str) -> str: + """Strip exchange multiplier prefixes without mangling tickers that start with 'K' (e.g. KAVA, KAS, KSM).""" + if not raw_base: + return "" + stripped = re.sub(r'^(1000000000|1000000|100000|10000|1000)(?=.)', '', raw_base) + if stripped != raw_base: + return stripped.upper() + if raw_base.startswith("k") and len(raw_base) > 1 and raw_base[1].isupper(): + return raw_base[1:].upper() + upper_base = raw_base.upper() + if upper_base.startswith("K") and upper_base[1:] in _KNOWN_K_MULTIPLIER_BASES: + return upper_base[1:] + return upper_base + def strip_multiplier_prefix(symbol: str) -> str: """ Strip exchange contract multiplier prefixes (1000, 10000, 1000000, 1000000000, k/K) - from normalized symbols such as 1000PEPEUSDT -> PEPEUSDT, while preserving tokens like 1INCHUSDT. + from normalized symbols such as 1000PEPEUSDT -> PEPEUSDT, while preserving tokens like 1INCHUSDT and KAVAUSDT. """ if not symbol: return "" - s = str(symbol).strip().upper().replace("/", "").replace("-", "").replace("_", "").replace(" ", "") + raw = str(symbol).strip().replace("/", "").replace("-", "").replace("_", "").replace(" ", "") quote = "" + raw_upper = raw.upper() for q in ("USDT", "USDC", "USD", "BUSD", "EUR"): - if s.endswith(q) and len(s) > len(q): + if raw_upper.endswith(q) and len(raw) > len(q): quote = q - s = s[:-len(q)] + raw = raw[:-len(q)] break - bare = re.sub(r'^(1000000000|1000000|100000|10000|1000|k)', '', s, flags=re.IGNORECASE) + bare = _strip_multiplier_from_base(raw) if not bare: - bare = s + bare = raw.upper() return f"{bare}{quote}" @@ -38,19 +57,23 @@ def get_symbol_variations(symbol: str) -> list[str]: """ if not symbol: return [] - s = str(symbol).strip().replace("/", "").replace("-", "").replace("_", "").replace(" ", "") + raw = str(symbol).strip().replace("/", "").replace("-", "").replace("_", "").replace(" ", "") quote = "USDT" + raw_upper = raw.upper() for q in ("USDT", "USDC", "USD", "BUSD", "EUR"): - if s.upper().endswith(q): + if raw_upper.endswith(q) and len(raw) > len(q): quote = q - s = s[:-len(q)] + raw = raw[:-len(q)] break - # Strip existing multiplier prefix if present to get the clean bare token name - bare = re.sub(r'^(1000000000|1000000|100000|10000|1000|k)', '', s, flags=re.IGNORECASE) + upper_base = raw.upper() + bare = _strip_multiplier_from_base(raw) - bases = [s, bare, f"1000{bare}", f"10000{bare}", f"1000000{bare}", f"k{bare}", f"K{bare}"] + bases = [upper_base, bare] + if raw != upper_base and raw not in bases: + bases.append(raw) + bases.extend([f"1000{bare}", f"10000{bare}", f"1000000{bare}", f"k{bare}", f"K{bare}"]) unique_bases = [] for b in bases: if b and b not in unique_bases: diff --git a/backend/exchanges/base.py b/backend/exchanges/base.py index 7e1b8b637c622b46cc13bd747c59257b84538620..4bb8ead20e35057181d05c92cb0c50eafec1691d 100644 --- a/backend/exchanges/base.py +++ b/backend/exchanges/base.py @@ -5,6 +5,7 @@ All methods are async-first and must NOT block the event loop. """ from abc import ABC, abstractmethod +import time from typing import Any @@ -93,6 +94,65 @@ class BaseExchange(ABC): # Convenience # ------------------------------------------------------------------ + def _record_oi_change( + self, + symbol_key: str, + current_oi: float, + window_sec: float = 300.0, + min_sample_gap_sec: float = 30.0, + max_age_sec: float = 3600.0, + ) -> float | None: + """Compute percentage OI change against a rolling ~5m (or oldest recent) baseline.""" + if current_oi <= 0: + return None + snaps_map = getattr(self, "_oi_snapshots", None) + if snaps_map is None: + snaps_map = {} + self._oi_snapshots = snaps_map + now_ts = time.time() + raw_snaps = snaps_map.get(symbol_key, []) + # Drop stale snapshots (e.g. after long idle/sleep) to avoid spurious percentage jumps + snaps = [(ts, val) for ts, val in raw_snaps if (now_ts - ts) <= max_age_sec and val > 0] + snaps_map[symbol_key] = snaps + + oi_change_pct = None + if snaps: + anchor = next((val for ts, val in reversed(snaps) if (now_ts - ts) >= window_sec), snaps[0][1]) + if anchor > 0: + oi_change_pct = round((current_oi - anchor) / anchor * 100.0, 4) + + if not snaps or (now_ts - snaps[-1][0]) >= min_sample_gap_sec: + snaps.append((now_ts, current_oi)) + if len(snaps) > 64: + del snaps[:-64] + return oi_change_pct + + @staticmethod + def _compute_oi_horizons( + oi_series_oldest_first: list[float], + ) -> tuple[float | None, float | None, float | None]: + """Compute 15m, 1h (>=5 bars), and 4h (>=13 bars) OI % changes without mislabeling short history.""" + if len(oi_series_oldest_first) < 2: + return None, None, None + + curr_oi = oi_series_oldest_first[-1] + prev_15m = oi_series_oldest_first[-2] + oi_15m = round(((curr_oi - prev_15m) / prev_15m) * 100.0, 4) if prev_15m > 0 else None + + oi_1h = None + if len(oi_series_oldest_first) >= 5: + prev_1h = oi_series_oldest_first[-5] + if prev_1h > 0: + oi_1h = round(((curr_oi - prev_1h) / prev_1h) * 100.0, 4) + + oi_4h = None + if len(oi_series_oldest_first) >= 13: + prev_4h = oi_series_oldest_first[max(0, len(oi_series_oldest_first) - 17)] + if prev_4h > 0: + oi_4h = round(((curr_oi - prev_4h) / prev_4h) * 100.0, 4) + + return oi_15m, oi_1h, oi_4h + async def get_full_snapshot(self, symbol: str) -> dict[str, Any]: """ Collect all data for a symbol in one call. diff --git a/backend/exchanges/binance.py b/backend/exchanges/binance.py index ad40b710798f396902e1a4ccd47f8feec4729975..bd5ebf1a558e91a5a90dcfaef818e24fa7b73266 100644 --- a/backend/exchanges/binance.py +++ b/backend/exchanges/binance.py @@ -24,9 +24,12 @@ logger = logging.getLogger(__name__) # Timeframe mapping: our standard → Binance kline interval TF_MAP = { "1m": "1m", + "3m": "3m", "5m": "5m", "15m": "15m", + "30m": "30m", "1h": "1h", + "2h": "2h", "4h": "4h", "1d": "1d", } @@ -124,7 +127,7 @@ class BinanceClient(BaseExchange): # Check negative cache to avoid spamming failed probes on every 60s loop import time now = time.time() - if symbol in self._negative_cache and (now - self._negative_cache[symbol] < 900): + if sym in self._negative_cache and (now - self._negative_cache[sym] < 900): return False # 2. If known symbols empty, trigger bulk load first @@ -155,7 +158,7 @@ class BinanceClient(BaseExchange): if self._known_symbols and sym in self._known_symbols: return True - self._negative_cache[symbol] = now + self._negative_cache[sym] = now return False async def get_mark_price(self, symbol: str) -> dict[str, Any]: @@ -185,32 +188,46 @@ class BinanceClient(BaseExchange): } async def get_open_interest(self, symbol: str) -> dict[str, Any]: - """Fetch current and 15m historical Open Interest to compute change %.""" + """Fetch current and multi-horizon (15m, 1h, 4h) historical Open Interest to compute change %.""" sym = self.resolve_symbol(symbol) if not sym: - return {"open_interest": 0.0, "prev_open_interest": None, "oi_change_pct": 0.0, "open_interest_value": None} + return { + "open_interest": 0.0, + "prev_open_interest": None, + "oi_change_pct": None, + "oi_change_1h_pct": None, + "oi_change_4h_pct": None, + "open_interest_value": None, + } try: hist = await self._get( "/futures/data/openInterestHist", - {"symbol": sym, "period": "15m", "limit": 2}, + {"symbol": sym, "period": "15m", "limit": 17}, ) if isinstance(hist, list) and len(hist) >= 2: - # Binance returns oldest to newest: hist[0] is prev, hist[1] is curr - prev_oi = float(hist[0].get("sumOpenInterest", 0)) - curr_oi = float(hist[1].get("sumOpenInterest", 0)) - oi_change_pct = ((curr_oi - prev_oi) / prev_oi * 100) if prev_oi else 0.0 + # Binance returns oldest to newest: hist[-1] is curr, hist[-2] is prev 15m + series = [float(item.get("sumOpenInterest", 0) or 0) for item in hist] + curr_item = hist[-1] + curr_oi = series[-1] + prev_oi = series[-2] + oi_15m, oi_1h, oi_4h = self._compute_oi_horizons(series) + return { "open_interest": curr_oi, "prev_open_interest": prev_oi, - "oi_change_pct": round(oi_change_pct, 4), - "open_interest_value": float(hist[1].get("sumOpenInterestValue", 0)) if hist[1].get("sumOpenInterestValue") else None, + "oi_change_pct": oi_15m, + "oi_change_1h_pct": oi_1h, + "oi_change_4h_pct": oi_4h, + "open_interest_value": float(curr_item.get("sumOpenInterestValue", 0)) if curr_item.get("sumOpenInterestValue") else None, } elif isinstance(hist, list) and len(hist) == 1: curr_oi = float(hist[0].get("sumOpenInterest", 0)) return { "open_interest": curr_oi, "prev_open_interest": None, - "oi_change_pct": 0.0, + "oi_change_pct": None, + "oi_change_1h_pct": None, + "oi_change_4h_pct": None, "open_interest_value": float(hist[0].get("sumOpenInterestValue", 0)) if hist[0].get("sumOpenInterestValue") else None, } except Exception as exc: @@ -221,45 +238,70 @@ class BinanceClient(BaseExchange): return { "open_interest": float(data.get("openInterest", 0)), "prev_open_interest": None, - "oi_change_pct": 0.0, + "oi_change_pct": None, + "oi_change_1h_pct": None, + "oi_change_4h_pct": None, "open_interest_value": None, } async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]: - """Top-trader account L/S ratio.""" + """Fetch Whale Top-Trader Position/Account L/S ratios alongside Global Retail L/S ratio.""" sym = self.resolve_symbol(symbol) if not sym: return {"long_ratio": None, "short_ratio": None, "source": "unavailable"} - try: - data = await self._get( - "/futures/data/topLongShortAccountRatio", - {"symbol": sym, "period": period, "limit": 1}, - ) - if data and "longAccount" in data[0]: - return { - "long_ratio": float(data[0]["longAccount"]), - "short_ratio": float(data[0]["shortAccount"]), - "source": "top_trader", - } - except Exception: - pass - try: - # Fallback: global L/S ratio - data = await self._get( - "/futures/data/globalLongShortAccountRatio", - {"symbol": sym, "period": period, "limit": 1}, - ) - if data and "longAccount" in data[0]: - return { - "long_ratio": float(data[0]["longAccount"]), - "short_ratio": float(data[0]["shortAccount"]), - "source": "global", - } - except Exception: - pass + async def _fetch_ls(endpoint: str) -> tuple[float, float] | None: + try: + data = await self._get(endpoint, {"symbol": sym, "period": period, "limit": 1}) + if isinstance(data, list) and data and "longAccount" in data[0]: + return float(data[0]["longAccount"]), float(data[0]["shortAccount"]) + except Exception: + pass + return None - return {"long_ratio": None, "short_ratio": None, "source": "unavailable"} + top_acc, global_acc, top_pos = await asyncio.gather( + _fetch_ls("/futures/data/topLongShortAccountRatio"), + _fetch_ls("/futures/data/globalLongShortAccountRatio"), + _fetch_ls("/futures/data/topLongShortPositionRatio"), + ) + + top_acc_long = top_acc[0] if top_acc else None + global_acc_long = global_acc[0] if global_acc else None + top_pos_long = top_pos[0] if top_pos else None + + # Retail global account ratio is the true contrarian crowd indicator; fallback to top_acc or top_pos + primary_long = ( + global_acc_long + if global_acc_long is not None + else (top_acc_long if top_acc_long is not None else top_pos_long) + ) + if primary_long is None: + return {"long_ratio": None, "short_ratio": None, "source": "unavailable"} + + primary_short = ( + global_acc[1] + if global_acc is not None + 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))) + ) + whale_delta = ( + round(top_pos_long - global_acc_long, 4) + if (top_pos_long is not None and global_acc_long is not None) + else 0.0 + ) + source = ( + "smart_money" + if (top_pos_long is not None and global_acc_long is not None) + else ("top_trader" if top_acc_long is not None else "global") + ) + return { + "long_ratio": primary_long, + "short_ratio": primary_short, + "top_position_long_ratio": top_pos_long, + "top_account_long_ratio": top_acc_long, + "retail_long_ratio": global_acc_long, + "whale_retail_delta": whale_delta, + "source": source, + } async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100) -> list[dict]: sym = self.resolve_symbol(symbol) or symbol @@ -270,17 +312,21 @@ class BinanceClient(BaseExchange): ) candles = [] for k in data: - candles.append( - { - "timestamp": k[0], - "open": float(k[1]), - "high": float(k[2]), - "low": float(k[3]), - "close": float(k[4]), - "volume": float(k[5]), - "taker_buy_volume": float(k[9]), - } - ) + c_dict: dict[str, Any] = { + "timestamp": k[0], + "open": float(k[1]), + "high": float(k[2]), + "low": float(k[3]), + "close": float(k[4]), + "volume": float(k[5]), + } + if len(k) > 9 and k[9] is not None: + c_dict["taker_buy_volume"] = float(k[9]) + if len(k) > 7 and k[7] is not None: + c_dict["quote_volume"] = float(k[7]) + if len(k) > 10 and k[10] is not None: + c_dict["taker_buy_quote_volume"] = float(k[10]) + candles.append(c_dict) return candles async def get_recent_trades(self, symbol: str, limit: int = 500) -> list[dict]: @@ -293,6 +339,7 @@ class BinanceClient(BaseExchange): "qty": float(t["qty"]), "is_buyer_maker": bool(t.get("isBuyerMaker", False)), "time": int(t["time"]), + "venue": "binance", } for t in data ] @@ -301,10 +348,11 @@ class BinanceClient(BaseExchange): async def get_spot_trades(self, symbol: str, limit: int = 500) -> list[dict]: """Fetch spot trades from Binance Spot API for Spot CVD vs Futures CVD analysis.""" - import re - clean_symbol = re.sub(r'^(1000000000|1000000|100000|10000|1000|k)', '', symbol, flags=re.IGNORECASE).upper() - symbols_to_try = [symbol] - if clean_symbol != symbol and clean_symbol.endswith("USDT"): + from engine.symbol_resolver import strip_multiplier_prefix + raw_sym = symbol.upper().strip().replace("/", "").replace("-", "") + clean_symbol = strip_multiplier_prefix(symbol) + symbols_to_try = [raw_sym] + if clean_symbol and clean_symbol != raw_sym and clean_symbol.endswith(("USDT", "USDC", "USD", "BUSD", "EUR")): symbols_to_try.append(clean_symbol) data = [] @@ -330,6 +378,7 @@ class BinanceClient(BaseExchange): "qty": float(t["qty"]), "is_buyer_maker": bool(t.get("isBuyerMaker", False)), "time": int(t["time"]), + "venue": "binance_spot", } for t in data ] diff --git a/backend/exchanges/bitget.py b/backend/exchanges/bitget.py index 33e2b202873aab17af197130ac3785a223607d9d..8f83fb4726662736457ec0b0c2be8b50c12eef65 100644 --- a/backend/exchanges/bitget.py +++ b/backend/exchanges/bitget.py @@ -23,9 +23,12 @@ BITGET_BASE_URL = "https://api.bitget.com" TIMEFRAME_MAP = { "1m": "1m", + "3m": "3m", "5m": "5m", "15m": "15m", + "30m": "30m", "1h": "1H", + "2h": "2H", "4h": "4H", "1d": "1Dutc", } @@ -73,7 +76,7 @@ class BitgetClient(BaseExchange): resolved = self.resolve_symbol(symbol) if resolved: return resolved - return symbol.upper().strip() + return symbol.upper().replace("/", "").replace("-", "").replace("_", "").replace(" ", "").strip() async def _get(self, path: str, params: dict | None = None) -> Any: try: @@ -207,21 +210,24 @@ class BitgetClient(BaseExchange): sym = self._to_bitget_symbol(symbol) data = await self._get("/api/v2/mix/market/open-interest", {"productType": "USDT-FUTURES", "symbol": sym}) if not data or not isinstance(data, dict): - return {"open_interest": None, "open_interest_value": None} + return {"open_interest": None, "open_interest_value": None, "oi_change_pct": None} oi_list = data.get("openInterestList", []) if not oi_list: - return {"open_interest": None, "open_interest_value": None} + return {"open_interest": None, "open_interest_value": None, "oi_change_pct": None} try: size_coins = float(oi_list[0].get("size", 0.0)) mp_data = await self.get_mark_price(symbol) - mp = mp_data.get("mark_price") or 1.0 - oi_usd = size_coins * mp + mp = mp_data.get("mark_price") + oi_usd = round(size_coins * float(mp), 2) if mp is not None and float(mp) > 0 else None + + oi_change_pct = self._record_oi_change(sym, size_coins) + return { "open_interest": round(size_coins, 4), - "open_interest_value": round(oi_usd, 2), - "oi_change_pct": None, + "open_interest_value": oi_usd, + "oi_change_pct": oi_change_pct, } except (ValueError, TypeError): return {"open_interest": None, "open_interest_value": None, "oi_change_pct": None} @@ -307,12 +313,13 @@ class BitgetClient(BaseExchange): { "price": float(f["price"]), "qty": float(f["size"]), - "is_buyer_maker": f.get("side") == "sell", + "is_buyer_maker": str(f.get("side", "")).strip().lower() == "sell", "time": int(f.get("ts", 0)), } ) except (KeyError, ValueError, TypeError): continue + trades.sort(key=lambda x: x["time"]) return trades async def get_orderbook(self, symbol: str, depth: int = 20) -> dict[str, Any]: @@ -329,8 +336,15 @@ class BitgetClient(BaseExchange): return {"bids": [], "asks": []} try: - bids = [[float(b[0]), float(b[1])] for b in data.get("bids", [])[:depth] if len(b) >= 2] - asks = [[float(a[0]), float(a[1])] for a in data.get("asks", [])[:depth] if len(a) >= 2] + bids = sorted( + ([float(b[0]), float(b[1])] for b in data.get("bids", []) if len(b) >= 2), + key=lambda x: x[0], + reverse=True, + )[:depth] + asks = sorted( + ([float(a[0]), float(a[1])] for a in data.get("asks", []) if len(a) >= 2), + key=lambda x: x[0], + )[:depth] return {"bids": bids, "asks": asks} except (ValueError, TypeError): return {"bids": [], "asks": []} diff --git a/backend/exchanges/bybit.py b/backend/exchanges/bybit.py index ec0b3824140522a97ab6d0bea35fff8ea08da40a..9790558ff7f534e584bb9df04307e7fa6d554ebf 100644 --- a/backend/exchanges/bybit.py +++ b/backend/exchanges/bybit.py @@ -20,9 +20,12 @@ logger = logging.getLogger(__name__) TF_MAP = { "1m": "1", + "3m": "3", "5m": "5", "15m": "15", + "30m": "30", "1h": "60", + "2h": "120", "4h": "240", "1d": "D", } @@ -115,7 +118,7 @@ class BybitClient(BaseExchange): # Check negative cache to avoid spamming failed probes on every 60s loop import time now = time.time() - if symbol in self._negative_cache and (now - self._negative_cache[symbol] < 900): + if sym in self._negative_cache and (now - self._negative_cache[sym] < 900): return False # 2. If known symbols empty, trigger bulk load first @@ -152,7 +155,7 @@ class BybitClient(BaseExchange): if self._known_symbols and sym in self._known_symbols: return True - self._negative_cache[symbol] = now + self._negative_cache[sym] = now return False async def get_mark_price(self, symbol: str) -> dict[str, Any]: @@ -165,8 +168,8 @@ class BybitClient(BaseExchange): if not items: raise ValueError(f"No ticker data for {sym}") t = items[0] - mark = float(t.get("markPrice", 0)) - index = float(t.get("indexPrice", 0)) + mark = float(t.get("markPrice") or 0) + index = float(t.get("indexPrice") or 0) basis_pct = ((mark - index) / index * 100) if index else 0.0 return { "mark_price": mark, @@ -185,54 +188,76 @@ class BybitClient(BaseExchange): raise ValueError(f"No ticker data for {sym}") t = items[0] return { - "funding_rate": float(t.get("fundingRate", 0)), + "funding_rate": float(t.get("fundingRate") or 0), "next_funding_time": t.get("nextFundingTime"), } async def get_open_interest(self, symbol: str) -> dict[str, Any]: - """Fetch current and 15m historical Open Interest from Bybit.""" + """Fetch current and multi-horizon (15m, 1h, 4h) historical Open Interest from Bybit.""" sym = self.resolve_symbol(symbol) if not sym: - return {"open_interest": 0.0, "prev_open_interest": None, "oi_change_pct": 0.0, "open_interest_value": None} + return { + "open_interest": 0.0, + "prev_open_interest": None, + "oi_change_pct": None, + "oi_change_1h_pct": None, + "oi_change_4h_pct": None, + "open_interest_value": None, + } + bulk_oi = bulk_fetcher.get_bybit_24h_and_oi(symbol) + bulk_oi_val = bulk_oi.get("open_interest_value") if bulk_oi else None try: result = await self._get( "/v5/market/open-interest", - {"category": "linear", "symbol": sym, "intervalTime": "15min", "limit": 2}, + {"category": "linear", "symbol": sym, "intervalTime": "15min", "limit": 17}, ) items = result.get("list", []) if len(items) >= 2: - # Bybit returns newest first: items[0] is curr, items[1] is prev - curr_oi = float(items[0].get("openInterest", 0)) - prev_oi = float(items[1].get("openInterest", 0)) - oi_change_pct = ((curr_oi - prev_oi) / prev_oi * 100) if prev_oi else 0.0 + # Bybit returns newest first: reverse to oldest->newest for shared horizon calculation + series = [float(item.get("openInterest", 0) or 0) for item in reversed(items)] + curr_oi = series[-1] + prev_oi = series[-2] + oi_15m, oi_1h, oi_4h = self._compute_oi_horizons(series) return { "open_interest": curr_oi, "prev_open_interest": prev_oi, - "oi_change_pct": round(oi_change_pct, 4), - "open_interest_value": None, + "oi_change_pct": oi_15m, + "oi_change_1h_pct": oi_1h, + "oi_change_4h_pct": oi_4h, + "open_interest_value": bulk_oi_val, } elif items: curr_oi = float(items[0].get("openInterest", 0)) return { "open_interest": curr_oi, "prev_open_interest": None, - "oi_change_pct": 0.0, - "open_interest_value": None, + "oi_change_pct": None, + "oi_change_1h_pct": None, + "oi_change_4h_pct": None, + "open_interest_value": bulk_oi_val, } except Exception as exc: logger.debug("[Bybit] OI fetch note for %s: %s", sym, exc) # Fallback to bulk ticker OI if available - bulk_oi = bulk_fetcher.get_bybit_24h_and_oi(symbol) if bulk_oi and bulk_oi.get("open_interest"): return { "open_interest": bulk_oi["open_interest"], "prev_open_interest": None, - "oi_change_pct": 0.0, - "open_interest_value": bulk_oi.get("open_interest_value"), + "oi_change_pct": None, + "oi_change_1h_pct": None, + "oi_change_4h_pct": None, + "open_interest_value": bulk_oi_val, } - return {"open_interest": 0.0, "prev_open_interest": None, "oi_change_pct": 0.0, "open_interest_value": None} + return { + "open_interest": 0.0, + "prev_open_interest": None, + "oi_change_pct": None, + "oi_change_1h_pct": None, + "oi_change_4h_pct": None, + "open_interest_value": None, + } async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]: """ @@ -311,29 +336,36 @@ class BybitClient(BaseExchange): async def get_spot_trades(self, symbol: str, limit: int = 500) -> list[dict]: """Fetch spot trades from Bybit Spot market for Spot vs Futures CVD divergence analysis.""" from engine.data_collector import _clean_spot_symbol + raw_sym = symbol.upper().replace("-", "").replace("/", "").replace("_", "").strip() spot_sym = _clean_spot_symbol(symbol) + probe_syms = [raw_sym] if raw_sym == spot_sym else [raw_sym, spot_sym] limit = min(limit, 1000) - try: - result = await self._get( - "/v5/market/recent-trade", - {"category": "spot", "symbol": spot_sym, "limit": limit}, - ) - trades = [] - for t in result.get("list", []): - side = str(t.get("side", "Buy")).strip().lower() - is_buyer_maker = (side == "sell") - trades.append( - { - "price": float(t["price"]), - "qty": float(t["size"]), - "is_buyer_maker": is_buyer_maker, - "time": int(t["time"]), - } + for cand_sym in probe_syms: + try: + result = await self._get( + "/v5/market/recent-trade", + {"category": "spot", "symbol": cand_sym, "limit": limit}, ) - trades.sort(key=lambda t: t["time"]) - return trades - except Exception: - return [] + raw_list = result.get("list") or [] + if not raw_list: + continue + trades = [] + for t in raw_list: + side = str(t.get("side", "Buy")).strip().lower() + is_buyer_maker = (side == "sell") + trades.append( + { + "price": float(t["price"]), + "qty": float(t["size"]), + "is_buyer_maker": is_buyer_maker, + "time": int(t["time"]), + } + ) + trades.sort(key=lambda t: t["time"]) + return trades + except Exception: + continue + return [] async def get_orderbook(self, symbol: str, depth: int = 20) -> dict[str, Any]: sym = self.resolve_symbol(symbol) or symbol diff --git a/backend/exchanges/hyperliquid.py b/backend/exchanges/hyperliquid.py index b06699b90ca6c12f521c8fcf946c76a41ab80dbb..41bf1c8dd6ccdc5dd1a3d2a1926abda90fe1513b 100644 --- a/backend/exchanges/hyperliquid.py +++ b/backend/exchanges/hyperliquid.py @@ -44,10 +44,10 @@ class HyperliquidClient: self._lock = asyncio.Lock() def _format_symbol(self, symbol: str) -> str: - """Strip quote currency (e.g. BTCUSDT -> BTC) preserving case.""" - sym = str(symbol).strip() + """Strip delimiters & quote currency (e.g. BTC/USDT, kPEPE-USDT -> BTC, kPEPE) preserving case.""" + sym = str(symbol).replace("/", "").replace("-", "").replace("_", "").strip() for q in ("USDT", "USDC", "USD", "BUSD", "EUR"): - if sym.upper().endswith(q): + if sym.upper().endswith(q) and len(sym) > len(q): return sym[:-len(q)] return sym @@ -130,6 +130,58 @@ class HyperliquidClient: logger.debug("[Hyperliquid] Error fetching orderbook for %s: %s", coin, exc) return None + async def get_recent_trades(self, symbol: str, limit: int = 500) -> list[dict]: + """ + Fetch recent on-chain trades from Hyperliquid DEX including wallet addresses (`users`). + """ + await self._refresh_meta() + coin = self.resolve_coin(symbol) + if not coin: + return [] + try: + resp = await self._client.post( + HYPERLIQUID_INFO_URL, + json={"type": "recentTrades", "coin": coin}, + ) + resp.raise_for_status() + data = resp.json() + if not isinstance(data, list): + return [] + trades = [] + for t in data: + try: + px = float(t.get("px", 0.0)) + sz = float(t.get("sz", 0.0)) + if px <= 0 or sz <= 0: + continue + side_str = str(t.get("side", "B")).upper() + # In Hyperliquid: 'B' = Bid/Buy aggressor (is_buyer_maker=False), 'A' = Ask/Sell aggressor (is_buyer_maker=True) + is_buyer_maker = side_str in ("A", "SELL", "S") + users = t.get("users") + taker_wallet = None + if isinstance(users, list) and len(users) >= 2: + # Hyperliquid users tuple is [buyer, seller]: sell aggressor (is_buyer_maker=True) -> users[1], buy aggressor -> users[0] + raw_wallet = users[1] if is_buyer_maker else users[0] + if raw_wallet: + taker_wallet = str(raw_wallet) + trades.append({ + "price": px, + "qty": sz, + "is_buyer_maker": is_buyer_maker, + "time": int(t.get("time", 0) or 0), + "venue": "hyperliquid", + "taker_wallet": taker_wallet, + }) + except (ValueError, TypeError): + continue + trades.sort(key=lambda x: x["time"]) + if limit > 0 and len(trades) > limit: + trades = trades[-limit:] + return trades + except Exception as exc: + logger.debug("[Hyperliquid] Error fetching recentTrades for %s: %s", coin, exc) + return [] + async def get_market_data(self, symbol: str) -> dict[str, Any] | None: """ Fetch funding rate, open interest, mark price, and premium for symbol. diff --git a/backend/exchanges/okx.py b/backend/exchanges/okx.py index 241fe4ecc1ef2e9f8cebdc35701086d75c67b39a..b2d6c54fd20c0e24faf97a8b6d02e6b093554831 100644 --- a/backend/exchanges/okx.py +++ b/backend/exchanges/okx.py @@ -11,6 +11,7 @@ Provides: import asyncio import logging +import time from typing import Any import httpx @@ -28,9 +29,12 @@ OKX_BASE_URL = "https://www.okx.com" TF_MAP = { "1m": "1m", + "3m": "3m", "5m": "5m", "15m": "15m", + "30m": "30m", "1h": "1H", + "2h": "2H", "4h": "4H", "1d": "1D", } @@ -72,14 +76,18 @@ class OKXClient(BaseExchange): return None def _to_inst_id(self, symbol: str) -> str: - """Convert any symbol (e.g. BTCUSDT, 1000PEPEUSDT) -> OKX instId.""" + """Convert any symbol (e.g. BTCUSDT, BTC/USDC, 1000PEPEUSDT) -> OKX instId.""" resolved = self.resolve_inst_id(symbol) if resolved: return resolved - sym = symbol.upper().strip() - if sym.endswith("USDT"): - base = sym[:-4] - return f"{base}-USDT-SWAP" + raw_upper = symbol.upper().strip() + if raw_upper.endswith("-SWAP") and "-" in raw_upper[:-5]: + return raw_upper + sym = raw_upper.replace("/", "").replace("-", "").replace("_", "").replace(" ", "") + for quote in ("USDT", "USDC", "USD", "EUR"): + if sym.endswith(quote) and len(sym) > len(quote): + base = sym[:-len(quote)] + return f"{base}-{quote}-SWAP" return f"{sym}-SWAP" async def _get(self, path: str, params: dict | None = None) -> Any: @@ -120,10 +128,12 @@ class OKXClient(BaseExchange): if self.resolve_inst_id(symbol): return True + sym_key = symbol.strip().upper().replace("/", "").replace("-", "") + # Check negative cache to avoid spamming failed probes on every 60s loop import time now = time.time() - if symbol in self._negative_cache and (now - self._negative_cache[symbol] < 900): + if sym_key in self._negative_cache and (now - self._negative_cache[sym_key] < 900): return False # 2. Ensure known symbols are loaded via single bulk call @@ -133,7 +143,7 @@ class OKXClient(BaseExchange): return True # 3. Direct lightweight probe fallback (only target most probable instrument IDs) - clean = symbol.upper().replace("/", "").replace("-", "") + clean = sym_key base = clean[:-4] if clean.endswith("USDT") or clean.endswith("USDC") else clean candidates = [f"{base}-USDT-SWAP", f"{clean}-SWAP"] for inst_cand in candidates: @@ -146,13 +156,13 @@ class OKXClient(BaseExchange): if resp.status_code == 200: data = resp.json() if data.get("code") == "0" and len(data.get("data", [])) > 0: - self._known_symbols.add(symbol.upper()) - self._inst_map[symbol.upper()] = inst_cand + self._known_symbols.add(sym_key) + self._inst_map[sym_key] = inst_cand return True except Exception: pass - self._negative_cache[symbol] = now + self._negative_cache[sym_key] = now return False async def get_mark_price(self, symbol: str) -> dict[str, Any]: @@ -226,14 +236,18 @@ class OKXClient(BaseExchange): inst_id = self._to_inst_id(symbol) data = await self._get("/api/v5/public/open-interest", {"instType": "SWAP", "instId": inst_id}) if not data: - return {"open_interest": 0.0, "open_interest_value": None} + return {"open_interest": 0.0, "open_interest_value": None, "oi_change_pct": None} oi = float(data[0].get("oiCcy", 0.0)) # OKX returns oi (contracts), oiCcy (base coins), and oiUsd (USD notional value) oi_usd = data[0].get("oiUsd") oi_val = float(oi_usd) if oi_usd is not None and oi_usd != "" else None + + oi_change_pct = self._record_oi_change(inst_id, oi) + return { "open_interest": oi, "open_interest_value": oi_val, + "oi_change_pct": oi_change_pct, } async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]: @@ -254,6 +268,8 @@ class OKXClient(BaseExchange): if data and len(data) > 0: # OKX returns [ts, ratio] where ratio = long_accounts / short_accounts ratio = float(data[0][1]) + if ratio < 0: + return None # Convert ratio = L / S where L + S = 1 => L = ratio / (1 + ratio) long_ratio = ratio / (1.0 + ratio) short_ratio = 1.0 - long_ratio diff --git a/backend/main.py b/backend/main.py index a8eb0da102e57349ad7700cea26d7e610eec5cf0..f26a9d0438ef5135ecab97635ae04cfe94cf1ccf 100644 --- a/backend/main.py +++ b/backend/main.py @@ -68,6 +68,15 @@ from engine.doh_resolver import enable_doh_bypass enable_doh_bypass() signal_engine = SignalEngine() +_background_tasks: set[asyncio.Task] = set() + + +def _spawn_background_task(coro: Any) -> asyncio.Task: + """Create a background task with a strong reference so GC cannot drop it prematurely.""" + task = asyncio.create_task(coro) + _background_tasks.add(task) + task.add_done_callback(_background_tasks.discard) + return task # ───────────────────────────────────────────────────────────────────────────── @@ -385,12 +394,12 @@ async def lifespan(app: FastAPI): if not is_serverless: # Warm up symbol caches and bulk market pre-fetcher in non-blocking background tasks on persistent boot - asyncio.create_task(bulk_fetcher.refresh_if_stale(force=True)) - asyncio.create_task(binance._load_symbols()) - asyncio.create_task(bybit._load_symbols()) - asyncio.create_task(okx._load_symbols()) - asyncio.create_task(bitget._refresh_symbols_universe()) - asyncio.create_task(hyperliquid._refresh_meta()) + _spawn_background_task(bulk_fetcher.refresh_if_stale(force=True)) + _spawn_background_task(binance._load_symbols()) + _spawn_background_task(bybit._load_symbols()) + _spawn_background_task(okx._load_symbols()) + _spawn_background_task(bitget._refresh_symbols_universe()) + _spawn_background_task(hyperliquid._refresh_meta()) # Dedicated DB retention janitor worker (runs every 30 minutes in the background) async def _retention_janitor_loop(): @@ -628,7 +637,7 @@ async def add_pair(body: AddPairRequest, request: Request): pair = await async_get_pair(symbol) collector = getattr(request.app.state, "collector", None) if collector and pair: - asyncio.create_task(_process_pair(pair, collector)) + _spawn_background_task(_process_pair(pair, collector)) return pair binance: BinanceClient = request.app.state.binance @@ -694,7 +703,7 @@ async def add_pair(body: AddPairRequest, request: Request): # Immediately compute signal in background for the newly added pair collector = getattr(request.app.state, "collector", None) if collector: - asyncio.create_task(_process_pair(pair, collector)) + _spawn_background_task(_process_pair(pair, collector)) return pair @@ -783,7 +792,14 @@ if os.path.exists(STATIC_DIR): ): raise HTTPException(status_code=404, detail="Not Found") - target_file = os.path.join(STATIC_DIR, full_path) + static_root = os.path.realpath(STATIC_DIR) + target_file = os.path.realpath(os.path.join(static_root, full_path)) + try: + in_static = os.path.commonpath([static_root, target_file]) == static_root + except ValueError: + in_static = False + if not in_static: + raise HTTPException(status_code=404, detail="Not Found") if os.path.isfile(target_file): return FileResponse(target_file) diff --git a/backend/routers/ai.py b/backend/routers/ai.py index a3b6501733d5c9fbd47cfd0420613315db2b351e..078613d368f8b1bb1a73012f8717a2c3078d216d 100644 --- a/backend/routers/ai.py +++ b/backend/routers/ai.py @@ -8,9 +8,12 @@ import os import re import time import asyncio +import ipaddress import logging +import socket from datetime import datetime, timezone from typing import Any +from urllib.parse import urlparse import httpx from fastapi import APIRouter, HTTPException, Request @@ -49,6 +52,7 @@ def get_ai_http_client() -> httpx.AsyncClient: _AI_HTTP_CLIENT = httpx.AsyncClient( timeout=None, verify=True, + follow_redirects=False, limits=httpx.Limits( max_keepalive_connections=10, max_connections=25, @@ -262,18 +266,14 @@ def _build_ai_prompt( if snapshots: for s in snapshots: ex = s.get("exchange", "") - oi_val = s.get("oi") or s.get("open_interest") or 0.0 - px = s.get("mark_price") or mark_price - oi_usd = oi_val if oi_val > 1e6 else (oi_val * px if px else 0.0) + oi_usd = float(s.get("oi") or s.get("open_interest") or 0.0) if oi_usd > 0: total_oi_usd += oi_usd venue_oi_str_list.append(f"{ex.upper()}: {_fmt_usd(oi_usd)}") else: for ex, d in active_exch_data.items(): if not d: continue - oi_val = d.get("oi") or 0.0 - px = d.get("mark_price") or mark_price - oi_usd = oi_val if oi_val > 1e6 else (oi_val * px if px else 0.0) + oi_usd = float(d.get("oi") or d.get("open_interest") or 0.0) if oi_usd > 0: total_oi_usd += oi_usd venue_oi_str_list.append(f"{ex.upper()}: {_fmt_usd(oi_usd)}") @@ -288,10 +288,8 @@ def _build_ai_prompt( fr = d.get("funding_rate") if fr is not None: fr_vals.append(float(fr)) - oi_raw = float(d.get("oi") or d.get("open_interest") or 0.0) - px_raw = float(d.get("mark_price") or mark_price or 0.0) - oi_usd_w = oi_raw if oi_raw > 1e6 else (oi_raw * px_raw if px_raw > 0 else oi_raw) - fr_weights.append(oi_usd_w) + oi_usd_w = float(d.get("oi") or d.get("open_interest") or 0.0) + fr_weights.append(max(0.0, oi_usd_w)) avg_fr_8h = _oi_weighted_average(fr_vals, fr_weights) if fr_vals else 0.0 avg_fr_8h_pct = avg_fr_8h * 100 annualized_apr_pct = avg_fr_8h * 3 * 365 * 100 @@ -315,7 +313,7 @@ def _build_ai_prompt( bitget_ls = f"{bitget.get('long_ratio', 0)*100:.1f}%L" if bitget.get('long_ratio') else "N/A" cross = factors.get("cross_exchange") or {} - div_pct = cross.get("divergence_pct", 0.0) + div_pct = float(cross.get("divergence_pct") or 0.0) # 3. CVD & Flow spot_fut = factors.get("spot_futures_cvd") or {} @@ -327,42 +325,104 @@ def _build_ai_prompt( spot_status_str = "Pasar Spot Riil Terdaftar (Likuiditas Organik Ada)" if has_spot else "⚠️ PERP-ONLY (Sintetis 100%, rawan wick sweep & manipulasi bandar)" # Hyperliquid - hl_basis = hl.get("basis_pct", 0.0) + hl_basis = float(hl.get("basis_pct") or 0.0) hl_sig = factors.get("hyperliquid") or {} hl_label = hl_sig.get("label", "Equilibrium") # OI Divergence oi_div = factors.get("oi_divergence") or {} oi_div_str = oi_div.get("direction_val") or oi_div.get("value") or oi_div.get("label", "Balanced Market Flow") + oi_1h_pct = oi_div.get("oi_change_1h_pct") + oi_4h_pct = oi_div.get("oi_change_4h_pct") + oi_multi_parts = [] + if oi_1h_pct is not None: + oi_multi_parts.append(f"1H OI: {float(oi_1h_pct):+.2f}%") + if oi_4h_pct is not None: + oi_multi_parts.append(f"4H OI: {float(oi_4h_pct):+.2f}%") + if oi_multi_parts: + oi_div_str = f"{oi_div_str} ({' | '.join(oi_multi_parts)})" + + # Safe 5-layer whale telemetry formatting (prevents NoneType.__format__ and 0.0% hallucinations) + ls_factor = factors.get("ls_ratio") or {} + + def _wf_num(key: str, default: float) -> float: + val = whale_flow.get(key) + if val is None: + return default + try: + return float(val) + except (TypeError, ValueError): + return default + + wf_taker_buy_pct = _wf_num("taker_buy_pct", 50.0) + wf_taker_ratio = _wf_num("taker_ratio", 1.0) + wf_buy_count = int(_wf_num("whale_buy_count", 0)) + wf_sell_count = int(_wf_num("whale_sell_count", 0)) + wf_buy_vol = _wf_num("whale_buy_vol_usd", 0.0) + wf_sell_vol = _wf_num("whale_sell_vol_usd", 0.0) + wf_sweep_buy_cnt = int(_wf_num("sweep_buy_count", 0)) + wf_sweep_sell_cnt = int(_wf_num("sweep_sell_count", 0)) + wf_sweep_buy_vol = _wf_num("sweep_buy_vol_usd", 0.0) + wf_sweep_sell_vol = _wf_num("sweep_sell_vol_usd", 0.0) + wf_twap_bias = whale_flow.get("twap_bias") or "NEUTRAL" + wf_twap_buy_pct = _wf_num("twap_buy_pct", 50.0) + wf_abs_note = whale_flow.get("absorption_note") + wf_abs_type = whale_flow.get("absorption_type") + wf_absorption_str = ( + wf_abs_note + or (wf_abs_type if wf_abs_type and wf_abs_type != "NONE" else None) + or "Tidak ada" + ) + wf_whale_lr = whale_flow.get("whale_position_long_ratio") + if wf_whale_lr is None: + wf_whale_lr = ls_factor.get("whale_position_long_ratio") + wf_retail_lr = whale_flow.get("retail_account_long_ratio") + if wf_retail_lr is None: + wf_retail_lr = ls_factor.get("retail") + wf_sm_delta = whale_flow.get("smart_money_delta") + if wf_sm_delta is None: + wf_sm_delta = ls_factor.get("smart_money_delta") + wf_whale_lr_str = f"{float(wf_whale_lr) * 100:.1f}%" if wf_whale_lr is not None else "N/A" + wf_retail_lr_str = f"{float(wf_retail_lr) * 100:.1f}%" if wf_retail_lr is not None else "N/A" + wf_sm_delta_str = ( + f"{float(wf_sm_delta) * 100:+.1f}%" + if (wf_sm_delta is not None and (wf_whale_lr is not None or wf_retail_lr is not None)) + else "N/A" + ) + wf_onchain_wallets = int(_wf_num("onchain_whale_wallets", 0)) + wf_largest_usd = _wf_num("largest_trade_usd", 0.0) + wf_largest_side = whale_flow.get("largest_trade_side") or "NONE" + wf_verdict = whale_flow.get("flow_verdict") or "Order Flow Agregat Seimbang" # 4. Multi-Timeframe & Squeeze ms = factors.get("market_structure") or {} - active_tf = ms.get("tf", "1h") + active_tf = ms.get("tf") or "1h" struct_map = ms.get("structure_per_tf") or {} squeeze = pred.get("volatility_squeeze") or {} - squeeze_intensity = squeeze.get("squeeze_intensity", "NORMAL") - compression_ratio = squeeze.get("compression_ratio", 1.0) + squeeze_intensity = squeeze.get("squeeze_intensity") or "NORMAL" + raw_compression = squeeze.get("compression_ratio") + compression_ratio = float(raw_compression) if raw_compression is not None else 1.0 # Orderbook depth skew ob_skew = pred.get("orderbook_skew") or {} - resting_pressure = ob_skew.get("resting_pressure", "BALANCED") - bid_depth = ob_skew.get("bid_depth_usd", 0.0) - ask_depth = ob_skew.get("ask_depth_usd", 0.0) + resting_pressure = ob_skew.get("resting_pressure") or "BALANCED" + bid_depth = float(ob_skew.get("bid_depth_usd") or 0.0) + ask_depth = float(ob_skew.get("ask_depth_usd") or 0.0) depth_ratio = (bid_depth / ask_depth) if ask_depth > 0 else (99.0 if bid_depth > 0 else 1.0) # Liquidation Magnets & Predictive Targets magnets = pred.get("liquidation_magnets") or {} - upper_mag = magnets.get("upper_magnet_str", "N/A") - lower_mag = magnets.get("lower_magnet_str", "N/A") - dist_up = magnets.get("dist_upper_pct", 0.0) - dist_down = magnets.get("dist_lower_pct", 0.0) + upper_mag = magnets.get("upper_magnet_str") or "N/A" + lower_mag = magnets.get("lower_magnet_str") or "N/A" + dist_up = float(magnets.get("dist_upper_pct") or 0.0) + dist_down = float(magnets.get("dist_lower_pct") or 0.0) pred_target = pred.get("predicted_target") pred_target_str = _fmt_px(pred_target) if pred_target else "N/A" - target_type = pred.get("target_type", "N/A") - target_dist_pct = pred.get("target_dist_pct", 0.0) - anticipation_text = pred.get("anticipation", "Menunggu konfirmasi momentum likuiditas.") + target_type = pred.get("target_type") or "N/A" + target_dist_pct = float(pred.get("target_dist_pct") or 0.0) + anticipation_text = pred.get("anticipation") or "Menunggu konfirmasi momentum likuiditas." # 5. Confluence Consensus & Streak conviction = signal.get("conviction", 0) if signal else (signals_data.get("conviction", 0)) @@ -375,8 +435,12 @@ def _build_ai_prompt( neutral_signals = [] for k, v in factors.items(): if isinstance(v, dict): - sc = v.get("score", 0) - lbl = v.get("label", k) + try: + raw_sc = v.get("score", 0) + sc = int(float(raw_sc)) if raw_sc is not None else 0 + except (TypeError, ValueError): + sc = 0 + lbl = v.get("label") or k if sc > 0: bullish_signals.append(f"{k} (+{sc}): {lbl}") elif sc < 0: bearish_signals.append(f"{k} ({sc}): {lbl}") else: neutral_signals.append(f"{k} (0): {lbl}") @@ -411,7 +475,7 @@ def _build_ai_prompt( # 7. Fakeout / Manipulation Detector fake_det = factors.get("fake_detector") or {} is_fake = fake_det.get("is_fake", False) - fake_reason = fake_det.get("reason", "") + fake_reason = fake_det.get("reason") or "; ".join(fake_det.get("warnings") or []) fake_status_str = f"🚨 TERDETEKSI MANIPULASI HARGA: {fake_reason}" if is_fake else "✅ Bersih (Tidak terdeteksi anomali wick sweep / divergensi spread manipulatif)" # Pre-calculated trade levels (if existing in signal engine) @@ -543,6 +607,16 @@ PERATURAN KRITIS UNTUK DAMIAN: [1-2 poin tindakan taktis praktis menanggapi kondisi yang ditanyakan user] """ + ll_spread_bps = float(lead_lag.get("max_spread_bps") or 0.0) + ll_spread_usd = float(lead_lag.get("max_spread_usd") or 0.0) + ext_high = extremes.get("high_24h") or mark_price + ext_low = extremes.get("low_24h") or mark_price + ext_dist_high = float(extremes.get("dist_to_high_pct") or 0.0) + ext_dist_low = float(extremes.get("dist_to_low_pct") or 0.0) + ext_range_usd = float(extremes.get("range_usd") or 0.0) + ext_range_pct = float(extremes.get("range_pct") or 0.0) + ext_range_pos = float(extremes.get("range_position_pct") if extremes.get("range_position_pct") is not None else 50.0) + prompt = f"""Role: Damian — Senior Institutional Crypto Derivatives Quantitative Strategist. Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presisi kuantitatif, dan tanpa basa-basi pembuka/penutup. @@ -556,15 +630,15 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi 2. HARGA MULTI-BURSA, DISPARITAS LEAD-LAG & LIKUIDITAS • Mark Price Utama: {_fmt_px(mark_price)} | Index Price: {_fmt_px(index_price)} | Basis Spread: {div_pct:+.3f}% • 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)} - • 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')} + • 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'} • Total Open Interest Agregat (5 Bursa): {total_oi_str} ({venue_oi_breakdown}) • Status Pasar: {spot_status_str} 3. EXTREMES 24 JAM & PROFIL RENTANG HARGA - • 24H High: {_fmt_px(extremes.get('high_24h', mark_price))} ({extremes.get('dist_to_high_pct', 0.0):+.2f}% dari harga saat ini) - • 24H Low: {_fmt_px(extremes.get('low_24h', mark_price))} ({extremes.get('dist_to_low_pct', 0.0):+.2f}% dari harga saat ini) - • Rentang 24H: {_fmt_px(extremes.get('range_usd', 0.0))} ({extremes.get('range_pct', 0.0):.2f}% rentang volatilitas) - • Posisi Rentang: {extremes.get('range_position_pct', 50.0):.1f}% -> {extremes.get('zone_label', 'Equilibrium')} + • 24H High: {_fmt_px(ext_high)} ({ext_dist_high:+.2f}% dari harga saat ini) + • 24H Low: {_fmt_px(ext_low)} ({ext_dist_low:+.2f}% dari harga saat ini) + • Rentang 24H: {_fmt_px(ext_range_usd)} ({ext_range_pct:.2f}% rentang volatilitas) + • Posisi Rentang: {ext_range_pos:.1f}% -> {extremes.get('zone_label') or 'Equilibrium'} 4. FUNDING RATES, COUNTDOWN SETTLEMENT & ANNUALIZED CARRY (APR %) • 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 5. ORDER FLOW INSTITUSIONAL, WHALE BLOCK TRADES & CVD • Spot CVD: {spot_cvd} | Futures CVD: {fut_cvd} -> Status Aliran: {cvd_label} - • 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) - • 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}) - • Trade Terbesar: {_fmt_usd(whale_flow.get('largest_trade_usd', 0.0))} ({whale_flow.get('largest_trade_side', 'NONE')}) -> {whale_flow.get('flow_verdict', '')} + • Agresivitas Taker: Buy {wf_taker_buy_pct:.1f}% vs Sell {100.0 - wf_taker_buy_pct:.1f}% (Rasio Taker: {wf_taker_ratio:.2f}x) + • 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}) + • Whale TWAP & Iceberg Absorption: TWAP Bias: {wf_twap_bias} ({wf_twap_buy_pct:.1f}% Klines Taker Buy) | Absorption: {wf_absorption_str} + • 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} + • Trade Terbesar: {_fmt_usd(wf_largest_usd)} ({wf_largest_side}) -> {wf_verdict} • Hyperliquid DEX Whale Flow: {hl_label} (Basis Mark-Oracle: {hl_basis:+.3f}%) • Open Interest Divergence: {oi_div_str} 6. STRUKTUR MULTI-TIMEFRAME (MTF), VOLATILITAS & ORDERBOOK - • 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()}) + • 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()}) • Volatility Squeeze: {squeeze_intensity} (Compression Ratio: {compression_ratio:.2f}) • Radar Squeeze & Breakout: {breakout.get('radar_label')} | Stage: {breakout.get('squeeze_stage')} | Proyeksi Arah: {breakout.get('projected_direction')} • Katalis Breakout: {breakout.get('catalyst_summary')} @@ -610,8 +686,8 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi "mark_price_str": _fmt_px(mark_price), "total_oi_usd": total_oi_usd, "total_oi_str": total_oi_str, - "avg_fr_8h_pct": avg_fr_8h_pct, - "annualized_apr_pct": annualized_apr_pct, + "avg_fr_8h_pct": round(avg_fr_8h_pct, 4), + "annualized_apr_pct": round(annualized_apr_pct, 2), "triangulation_spread_pct": div_pct, "binance_fr": binance_fr, "bybit_fr": bybit_fr, @@ -646,22 +722,115 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi "leading_exchange": lead_lag.get("leading_exchange"), "funding_countdown": settlement.get("countdown_str"), "is_settlement_imminent": settlement.get("is_settlement_imminent"), - "taker_buy_pct": whale_flow.get("taker_buy_pct"), - "taker_ratio": whale_flow.get("taker_ratio"), - "whale_buy_count": whale_flow.get("whale_buy_count"), - "whale_sell_count": whale_flow.get("whale_sell_count"), - "whale_buy_vol_usd": whale_flow.get("whale_buy_vol_usd"), - "whale_sell_vol_usd": whale_flow.get("whale_sell_vol_usd"), + "taker_buy_pct": wf_taker_buy_pct, + "taker_ratio": wf_taker_ratio, + "whale_buy_count": wf_buy_count, + "whale_sell_count": wf_sell_count, + "whale_buy_vol_usd": wf_buy_vol, + "whale_sell_vol_usd": wf_sell_vol, + "sweep_buy_count": wf_sweep_buy_cnt, + "sweep_sell_count": wf_sweep_sell_cnt, + "sweep_buy_vol_usd": wf_sweep_buy_vol, + "sweep_sell_vol_usd": wf_sweep_sell_vol, + "twap_bias": wf_twap_bias, + "twap_buy_pct": wf_twap_buy_pct, + "absorption_type": wf_abs_type, + "absorption_note": wf_abs_note, + "whale_position_long_ratio": wf_whale_lr, + "retail_account_long_ratio": wf_retail_lr, + "smart_money_delta": wf_sm_delta, + "onchain_whale_wallets": wf_onchain_wallets, + "oi_change_1h_pct": oi_1h_pct, + "oi_change_4h_pct": oi_4h_pct, "breakout_radar": breakout, "market_structure": struct_map, "global_regime": regime_text, "fake_status": fake_status_str, - "warnings": signal.get("warnings") or [], + "warnings": (signal or {}).get("warnings") or [], } return prompt, data_summary +def resolve_ai_api_key( + provider: str, + body_api_key: str | None, + header_api_key: str | None, + base_url: str | None = None, +) -> str | None: + """Resolve API key safely: never fall back to server env secrets when custom endpoints are used.""" + explicit = (body_api_key or header_api_key or "").strip() + if explicit: + return explicit + prov = (provider or "").lower().strip() + if prov == "custom" or (base_url and base_url.strip()): + return None + env_var_map = { + "vikey": "VIKEY_API_KEY", + "gemini": "GEMINI_API_KEY", + "openai": "OPENAI_API_KEY", + "openrouter": "OPENROUTER_API_KEY", + "groq": "GROQ_API_KEY", + } + env_name = env_var_map.get(prov) + return os.getenv(env_name) if env_name else None + + +def _validate_ai_base_url(raw_url: str) -> str: + """Validate custom LLM base URL against unsafe schemes, userinfo, and private/internal IPs (SSRF).""" + b_url = raw_url.strip().rstrip("/") + parsed = urlparse(b_url) + if parsed.scheme not in ("http", "https") or not parsed.hostname: + raise HTTPException( + status_code=400, + detail="Custom base_url tidak valid (harus URL http/https yang sah).", + ) + if parsed.username or parsed.password: + raise HTTPException( + status_code=400, + detail="Custom base_url tidak boleh menyertakan kredensial userinfo.", + ) + + host = parsed.hostname.lower().rstrip(".") + if host in ("localhost", "localhost.localdomain") or host.endswith(".local") or host.endswith(".internal"): + raise HTTPException( + status_code=400, + detail="Custom base_url tidak diizinkan mengarah ke host internal atau lokal.", + ) + + try: + ip_obj = ipaddress.ip_address(host) + except ValueError: + ip_obj = None + + if ip_obj is not None: + if not ip_obj.is_global: + raise HTTPException( + status_code=400, + detail="Custom base_url tidak diizinkan mengarah ke IP privat, loopback, atau link-local.", + ) + else: + try: + addr_infos = socket.getaddrinfo(host, None) + except socket.gaierror: + addr_infos = [] + for info in addr_infos: + resolved_ip = info[4][0].split("%")[0] + try: + resolved_obj = ipaddress.ip_address(resolved_ip) + except ValueError: + continue + if not resolved_obj.is_global: + raise HTTPException( + status_code=400, + detail="Custom base_url resolves ke alamat IP privat atau internal yang dilarang.", + ) + + if not b_url.endswith("/v1") and "/v1" not in parsed.path: + b_url = f"{b_url}/v1" + return b_url + + async def execute_llm_completion( provider: str, clean_api_key: str, @@ -684,6 +853,11 @@ async def execute_llm_completion( """ clean_key = clean_api_key.strip().strip('"\'') prov = provider.lower().strip() + if base_url and base_url.strip() and prov != "custom": + raise HTTPException( + status_code=400, + detail=f"Parameter base_url hanya diizinkan untuk provider 'custom', bukan '{prov}'.", + ) client = get_ai_http_client() if prov == "gemini": @@ -753,18 +927,15 @@ async def execute_llm_completion( resolved_base_url = "https://openrouter.ai/api/v1" default_model = "anthropic/claude-3.5-sonnet" elif prov == "custom": - resolved_base_url = (base_url or "https://api.vikey.ai/v1").rstrip("/") + if base_url and base_url.strip(): + resolved_base_url = _validate_ai_base_url(base_url) + else: + resolved_base_url = "https://api.vikey.ai/v1" default_model = "anthropic/claude-fable-5" else: # openai resolved_base_url = "https://api.openai.com/v1" default_model = "gpt-4o-mini" - if base_url and base_url.strip(): - b_url = base_url.strip().rstrip("/") - if not b_url.endswith("/v1") and not "/v1" in b_url: - b_url = f"{b_url}/v1" - resolved_base_url = b_url - resolved_model = model_name.strip().strip('"\'') if (model_name and model_name.strip()) else default_model used_model = resolved_model @@ -948,7 +1119,10 @@ async def execute_llm_completion( return text_result, used_model else: - raise HTTPException(status_code=400, detail=f"Provider '{prov}' tidak didukung. Gunakan 'vikey', 'gemini', 'openai', atau 'groq'.") + raise HTTPException( + status_code=400, + detail=f"Provider '{prov}' tidak didukung. Gunakan 'vikey', 'gemini', 'openai', 'openrouter', 'groq', atau 'custom'.", + ) @router.post("/analyze") @@ -957,16 +1131,29 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request): AI Market Analysis endpoint. Includes in-memory 3-minute caching to eliminate token waste. """ - symbol = body.symbol.upper().strip() - if not symbol.endswith("USDT"): + symbol = body.symbol.upper().strip().replace("/", "").replace("-", "") + if not any(symbol.endswith(q) and len(symbol) > len(q) for q in ("USDT", "USDC", "USD", "BUSD", "EUR")): symbol = f"{symbol}USDT" + req_provider = body.provider.lower().strip() + validated_base_url = "" + if body.base_url and body.base_url.strip(): + if req_provider != "custom": + raise HTTPException( + status_code=400, + detail=f"Parameter base_url hanya diizinkan untuk provider 'custom', bukan '{req_provider}'.", + ) + validated_base_url = _validate_ai_base_url(body.base_url) + # Check cache first if no custom question and not forcing refresh now_ts = time.time() _prune_ai_cache(now_ts) - req_provider = body.provider.lower().strip() model_key = (body.model or "default").strip() - cache_key = f"{symbol}:{req_provider}:{model_key}" + cache_key = ( + f"{symbol}:{req_provider}:{model_key}:{validated_base_url}" + if validated_base_url + else f"{symbol}:{req_provider}:{model_key}" + ) cache_entry = _AI_CACHE.get(cache_key) 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): logger.info("[%s] Returning cached AI analysis (%s, age: %ds, 0 tokens burned)", symbol, cache_key, int(age_seconds)) return cached_data - # Resolve API Key - api_key = ( - body.api_key - or request.headers.get("x-api-key") - or (os.getenv("VIKEY_API_KEY") if req_provider == "vikey" - else os.getenv("GEMINI_API_KEY") if req_provider == "gemini" - else os.getenv("OPENAI_API_KEY")) + # Resolve API Key safely (never expose server env credentials to custom endpoints) + api_key = resolve_ai_api_key( + provider=req_provider, + body_api_key=body.api_key, + header_api_key=request.headers.get("x-api-key"), + base_url=body.base_url, ) if not api_key or not api_key.strip(): @@ -1007,7 +1193,9 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request): is_signal_stale = True if signal and signal.get("created_at"): try: - created_dt = datetime.fromisoformat(str(signal["created_at"])) + created_dt = datetime.fromisoformat(str(signal["created_at"]).replace("Z", "+00:00")) + if created_dt.tzinfo is None: + created_dt = created_dt.replace(tzinfo=timezone.utc) if (now_dt - created_dt).total_seconds() < 60: is_signal_stale = False except Exception: @@ -1038,16 +1226,16 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request): fresh_signal = eng.compute(raw) if fresh_signal: signal = fresh_signal - # Persist asynchronously so the DB and dashboard stay fresh without blocking - asyncio.create_task( - async_save_signal( + try: + await async_save_signal( symbol=symbol, timeframe=fresh_signal.get("active_timeframe", "adaptive"), direction=fresh_signal["direction"], conviction=fresh_signal["conviction"], signal_data=fresh_signal, ) - ) + except Exception as save_exc: + logger.debug("[%s] Failed to persist on-demand AI signal: %s", symbol, save_exc) except Exception as exc: logger.warning("[%s] On-demand live signal collect failed, using DB snapshot fallback: %s", symbol, exc) diff --git a/backend/routers/execution.py b/backend/routers/execution.py index 44131cc800558ec5a9765ce7c97e403e233ed4cb..fb2541313c86c6f83a7dfc90dadc0f529e935506 100644 --- a/backend/routers/execution.py +++ b/backend/routers/execution.py @@ -350,12 +350,19 @@ async def execute_bybit_order( journal_entry = None if body.log_to_journal: try: + def _fmt_exec_price(price: float) -> str: + if abs(price) >= 0.01 or price == 0: + return f"${price:,.4f}" + decimals = 10 if abs(price) < 0.0001 else 8 + return f"${price:.{decimals}f}".rstrip("0").rstrip(".") + bias_label = "STRONG LONG" if body.side.upper() in ("BUY", "LONG") else "STRONG SHORT" - tp_str = f"TP1: ${body.take_profit_1:,.4f} ({body.tp1_percent:.0f}%)" - if body.take_profit_2: - tp_str += f" | TP2: ${body.take_profit_2:,.4f} ({100 - body.tp1_percent:.0f}%)" + tp1_pct = body.tp1_percent if has_runner else 100.0 + tp_str = f"TP1: {_fmt_exec_price(body.take_profit_1)} ({tp1_pct:.0f}%)" + if has_runner and body.take_profit_2: + tp_str += f" | TP2: {_fmt_exec_price(body.take_profit_2)} ({100 - tp1_pct:.0f}%)" - entry_str = f"${body.entry_price:,.4f}" if body.entry_price else "MARKET ORDER" + entry_str = _fmt_exec_price(body.entry_price) if body.entry_price else "MARKET ORDER" margin_label = ( f"Margin: ${body.margin_usd:.1f} ({body.margin_percent:.1f}% eq) | Lev: {body.leverage}x" @@ -364,10 +371,10 @@ async def execute_bybit_order( ) journal_entry = await async_create_journal_entry({ - "symbol": body.symbol.upper(), + "symbol": body.symbol.upper().strip().replace("/", "").replace("-", "").replace("_", "").replace(" ", ""), "bias": bias_label, "entry_zone": entry_str, - "stop_loss": f"${body.stop_loss:,.4f}", + "stop_loss": _fmt_exec_price(body.stop_loss), "take_profit": tp_str, "risk_reward": margin_label, "leverage": f"{body.leverage}x", @@ -379,7 +386,7 @@ async def execute_bybit_order( "mode": exec_result.get("mode"), "margin_usd": body.margin_usd, "margin_percent": body.margin_percent, - "tp1_percent": body.tp1_percent, + "tp1_percent": tp1_pct, }, "status": "PENDING", }) diff --git a/backend/routers/journal.py b/backend/routers/journal.py index 68c32b51fbb44b4558264930d8117fd4ceb8fa86..838ad19370acc711a4d7b695f166118bd2243370 100644 --- a/backend/routers/journal.py +++ b/backend/routers/journal.py @@ -304,14 +304,14 @@ async def synthesize_damian_memory(body: SynthesizeAuditRequest, request: Reques detail="Tidak ada riwayat trade Stop Loss yang perlu diaudit saat ini.", ) - # 2. Resolve API key & endpoint + # 2. Resolve API key & endpoint safely (never expose server env keys to custom base_url) + from routers.ai import resolve_ai_api_key provider = body.provider.lower().strip() - api_key = ( - body.api_key - or request.headers.get("x-api-key") - or (os.getenv("VIKEY_API_KEY") if provider == "vikey" - else os.getenv("GEMINI_API_KEY") if provider == "gemini" - else os.getenv("OPENAI_API_KEY")) + api_key = resolve_ai_api_key( + provider=provider, + body_api_key=body.api_key, + header_api_key=request.headers.get("x-api-key"), + base_url=body.base_url, ) if not api_key or not api_key.strip(): diff --git a/backend/routers/market.py b/backend/routers/market.py index 0cb983f15a3596412507809dba6561136c940b31..9ca618091823724cbbd4bd0e0f70800c8f83c561 100644 --- a/backend/routers/market.py +++ b/backend/routers/market.py @@ -26,6 +26,38 @@ def _safe_get(data: Any, key: str, default: Any = None) -> Any: return default +def _extract_oi_usd( + oi_val: Any, + oi_coins: Any, + mark_price: Any, + fallback_price: float = 0.0, +) -> float | None: + """Resolve USD notional Open Interest across CEX/DEX venue payloads.""" + has_explicit_zero = False + try: + if oi_val is not None: + val_f = float(oi_val) + if val_f > 0: + return round(val_f, 2) + if val_f == 0: + has_explicit_zero = True + except (ValueError, TypeError): + pass + try: + if oi_coins is not None: + coins = float(oi_coins) + px = float(mark_price) if mark_price is not None else 0.0 + if px <= 0 and fallback_price > 0: + px = fallback_price + if coins > 0 and px > 0: + return round(coins * px, 2) + if coins == 0: + has_explicit_zero = True + except (ValueError, TypeError): + pass + return 0.0 if has_explicit_zero else None + + def _calculate_candle_delta(c: dict[str, Any] | None) -> float: """ Calculate directional or taker-volume delta for a single candle. @@ -44,7 +76,7 @@ def _calculate_candle_delta(c: dict[str, Any] | None) -> float: tbv = c.get("taker_buy_volume") if tbv is not None and str(tbv).strip() != "": try: - buy_vol = float(tbv) + buy_vol = max(0.0, min(vol, float(tbv))) sell_vol = max(0.0, vol - buy_vol) return buy_vol - sell_vol except (ValueError, TypeError): @@ -161,7 +193,7 @@ async def get_market_candles( exchanges_included.append(ex_name) m = {} for item in c_list: - s_ts = item.get("timestamp", 0) + s_ts = item.get("timestamp") or 0 s_sec = int(s_ts / 1000) if s_ts > 100_000_000_000 else int(s_ts) m[s_sec] = item aux_exchange_maps[ex_name] = m @@ -205,12 +237,14 @@ async def get_market_candles( ) # Sort candles chronologically by timestamp - raw_primary_candles.sort(key=lambda c: c.get("timestamp", 0)) + raw_primary_candles.sort(key=lambda c: c.get("timestamp") or 0) # Index OI data by time_sec binance_oi_map: dict[int, float] = {} for item in raw_binance_oi: - ts = int(item.get("timestamp", 0)) + ts = int(item.get("timestamp") or 0) + if ts <= 0: + continue sec = int(ts / 1000) if ts > 100_000_000_000 else ts oi_val = float(item.get("open_interest_usd") or 0.0) if oi_val > 0: @@ -218,7 +252,9 @@ async def get_market_candles( bybit_oi_map: dict[int, float] = {} for item in raw_bybit_oi: - ts = int(item.get("timestamp", 0)) + ts = int(item.get("timestamp") or 0) + if ts <= 0: + continue sec = int(ts / 1000) if ts > 100_000_000_000 else ts oi_coins = float(item.get("open_interest") or 0.0) if oi_coins > 0: @@ -250,7 +286,7 @@ async def get_market_candles( seen_times: set[int] = set() for c in raw_primary_candles: - ts = c.get("timestamp", 0) + ts = c.get("timestamp") or 0 time_sec = int(ts / 1000) if ts > 100_000_000_000 else int(ts) if time_sec in seen_times: continue @@ -391,40 +427,63 @@ async def get_multi_exchange_stream(symbol: str, request: Request): for k, r in zip(keys, res_list): results[k] = r if not isinstance(r, Exception) else None + def _first_present(*values): + for val in values: + if val is not None: + return val + return None + # Synthesize Binance binance_price = _safe_get(bnb_mp, "mark_price") or _safe_get(results.get("binance_mp"), "mark_price") binance_index = _safe_get(bnb_mp, "index_price") or _safe_get(results.get("binance_mp"), "index_price") - binance_funding = _safe_get(bnb_fr, "funding_rate") or _safe_get(results.get("binance_fr"), "funding_rate") - binance_oi = _safe_get(results.get("binance_oi"), "open_interest") + binance_funding = _first_present(_safe_get(bnb_fr, "funding_rate"), _safe_get(results.get("binance_fr"), "funding_rate")) + binance_oi_val = _safe_get(results.get("binance_oi"), "open_interest_value") + binance_oi_coins = _safe_get(results.get("binance_oi"), "open_interest") # Synthesize Bybit bybit_price = _safe_get(bybit_mp, "mark_price") or _safe_get(results.get("bybit_mp"), "mark_price") bybit_index = _safe_get(bybit_mp, "index_price") or _safe_get(results.get("bybit_mp"), "index_price") - bybit_funding = _safe_get(bybit_fr, "funding_rate") or _safe_get(results.get("bybit_fr"), "funding_rate") - bybit_oi = _safe_get(bybit_24h, "open_interest") or _safe_get(results.get("bybit_oi"), "open_interest") + bybit_funding = _first_present(_safe_get(bybit_fr, "funding_rate"), _safe_get(results.get("bybit_fr"), "funding_rate")) + bybit_oi_val = _first_present( + _safe_get(bybit_24h, "open_interest_value"), + _safe_get(results.get("bybit_oi"), "open_interest_value"), + ) + bybit_oi_coins = _first_present( + _safe_get(bybit_24h, "open_interest"), + _safe_get(results.get("bybit_oi"), "open_interest"), + ) # Synthesize OKX okx_price = _safe_get(results.get("okx_mp"), "mark_price") okx_index = _safe_get(results.get("okx_mp"), "index_price") okx_funding = _safe_get(results.get("okx_fr"), "funding_rate") - okx_oi = _safe_get(results.get("okx_oi"), "open_interest") + okx_oi_val = _safe_get(results.get("okx_oi"), "open_interest_value") + okx_oi_coins = _safe_get(results.get("okx_oi"), "open_interest") # Synthesize Bitget bitget_price = _safe_get(results.get("bitget_mp"), "mark_price") bitget_index = _safe_get(results.get("bitget_mp"), "index_price") bitget_funding = _safe_get(results.get("bitget_fr"), "funding_rate") - bitget_oi = _safe_get(results.get("bitget_oi"), "open_interest") + bitget_oi_val = _safe_get(results.get("bitget_oi"), "open_interest_value") + bitget_oi_coins = _safe_get(results.get("bitget_oi"), "open_interest") # Synthesize Hyperliquid hl_res = results.get("hl_data") hl_price = _safe_get(hl_res, "mark_price") hl_funding = _safe_get(hl_res, "funding_rate") - hl_oi = _safe_get(hl_res, "open_interest") + hl_oi_coins = _safe_get(hl_res, "open_interest") # Reference Price (average of valid mark prices) valid_prices = [p for p in (binance_price, bybit_price, okx_price, bitget_price, hl_price) if p and p > 0] ref_price = (sum(valid_prices) / len(valid_prices)) if valid_prices else 0.0 + # Resolve Open Interest strictly as USD notional so frontend $B/$M/$K formatting is consistent + binance_oi = _extract_oi_usd(binance_oi_val, binance_oi_coins, binance_price, fallback_price=ref_price) + bybit_oi = _extract_oi_usd(bybit_oi_val, bybit_oi_coins, bybit_price, fallback_price=ref_price) + okx_oi = _extract_oi_usd(okx_oi_val, okx_oi_coins, okx_price, fallback_price=ref_price) + bitget_oi = _extract_oi_usd(bitget_oi_val, bitget_oi_coins, bitget_price, fallback_price=ref_price) + hl_oi = _extract_oi_usd(None, hl_oi_coins, hl_price, fallback_price=ref_price) + def _diff_pct(p: float | None) -> float | None: if not p or not ref_price: return None @@ -522,7 +581,7 @@ async def get_market_funding_history( time_map: dict[int, dict[str, float | None]] = {} for ex_name in ("binance", "bybit", "okx", "bitget"): for item in results.get(ex_name, []): - raw_ts = int(item.get("timestamp", 0)) + raw_ts = int(item.get("timestamp") or 0) ts = int(raw_ts / 1000) if raw_ts > 100_000_000_000 else raw_ts # Settle intervals on standard funding epochs (aligned to hourly boundary) aligned_ts = round(ts / 3600) * 3600 diff --git a/backend/routers/signals.py b/backend/routers/signals.py index d85d773308f1bb4f62bcc3ca9dd66a7dd5a6b2e8..0cc8d220d05a053f91f9ce53746fbd29007a53f7 100644 --- a/backend/routers/signals.py +++ b/backend/routers/signals.py @@ -24,7 +24,7 @@ from database.db import ( from engine.outcome_evaluator import async_evaluate_pending_predictions, async_log_prediction_if_new from engine.signal_engine import SignalEngine from routers.ws import broadcast -from security import require_api_token +from security import require_api_token, require_cron_or_api_token router = APIRouter(prefix="/api/signals", tags=["signals"]) logger = logging.getLogger(__name__) @@ -57,7 +57,9 @@ async def get_all_signals(request: Request, background_tasks: BackgroundTasks): if not u_str: stale_count += 1 else: - dt = datetime.fromisoformat(u_str) + dt = datetime.fromisoformat(str(u_str).replace("Z", "+00:00")) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) if (now_dt - dt).total_seconds() > 120: stale_count += 1 except Exception: @@ -88,7 +90,7 @@ async def refresh_all_signals(request: Request): } -@router.get("/cron") +@router.get("/cron", dependencies=[Depends(require_cron_or_api_token)]) async def cron_refresh(request: Request): """Cron endpoint for Vercel/external schedulers to keep pairs refreshed.""" collector = getattr(request.app.state, "collector", None) diff --git a/backend/routers/ws.py b/backend/routers/ws.py index 629e127af981fedd6724edfdccb1f323635ebe16..af88074c83d029e78d8c65d6a7cc0a156125c4b2 100644 --- a/backend/routers/ws.py +++ b/backend/routers/ws.py @@ -8,6 +8,7 @@ WebSocket endpoints that stream signal and real-time chart updates to connected import asyncio import json import logging +import math import time from typing import Any @@ -23,11 +24,26 @@ router = APIRouter(tags=["websocket"]) _connections: set[WebSocket] = set() +def _sanitize_json_value(obj: Any) -> Any: + """Recursively replace non-finite floats (NaN/Inf) with None for RFC-8259 strict JSON.""" + if isinstance(obj, float): + return obj if math.isfinite(obj) else None + if isinstance(obj, dict): + return {k: _sanitize_json_value(v) for k, v in obj.items()} + if isinstance(obj, (list, tuple)): + return [_sanitize_json_value(v) for v in obj] + return obj + + +def _safe_json_dumps(data: Any) -> str: + return json.dumps(_sanitize_json_value(data), default=str, allow_nan=False) + + async def broadcast(data: Any) -> None: """Send a JSON payload to every connected WebSocket client concurrently with timeout guard.""" if not _connections: return - message = json.dumps(data, default=str) + message = _safe_json_dumps(data) clients = list(_connections) dead: set[WebSocket] = set() @@ -124,22 +140,53 @@ async def ws_chart(websocket: WebSocket, symbol: str): except Exception: pass - prices = [p for p in (price_binance, price_bybit) if p and p > 0] + price_okx = None + price_bitget = None + prices = [ + float(p) for p in (price_binance, price_bybit) + if p is not None and math.isfinite(float(p)) and float(p) > 0 + ] + + # Fallback to OKX and Bitget for pairs not listed on Binance or Bybit + if not prices: + if okx: + try: + mp = await okx.get_mark_price(clean_sym) + raw_okx = mp.get("mark_price") if isinstance(mp, dict) else None + if raw_okx is not None and math.isfinite(float(raw_okx)) and float(raw_okx) > 0: + price_okx = float(raw_okx) + except Exception: + pass + if bitget: + try: + mp = await bitget.get_mark_price(clean_sym) + raw_bg = mp.get("mark_price") if isinstance(mp, dict) else None + if raw_bg is not None and math.isfinite(float(raw_bg)) and float(raw_bg) > 0: + price_bitget = float(raw_bg) + except Exception: + pass + prices = [p for p in (price_okx, price_bitget) if p and p > 0] + live_price = prices[0] if prices else 0.0 if live_price > 0: now_ts = int(time.time()) + exchanges_payload: dict[str, Any] = { + "binance": price_binance, + "bybit": price_bybit, + } + if price_okx is not None: + exchanges_payload["okx"] = price_okx + if price_bitget is not None: + exchanges_payload["bitget"] = price_bitget payload = { "type": "chart_tick", "symbol": clean_sym, "time": now_ts, "price": live_price, - "exchanges": { - "binance": price_binance, - "bybit": price_bybit, - }, + "exchanges": exchanges_payload, } - await websocket.send_text(json.dumps(payload)) + await websocket.send_text(_safe_json_dumps(payload)) await asyncio.sleep(1.5) except (asyncio.CancelledError, WebSocketDisconnect, RuntimeError): break diff --git a/backend/scripts/run_backtest.py b/backend/scripts/run_backtest.py index 8a103b5abc6cb80ec70aec969d8d41534e4dcd13..60fd8f345127032d6ed8d891e67a7653be8a2160 100644 --- a/backend/scripts/run_backtest.py +++ b/backend/scripts/run_backtest.py @@ -62,6 +62,7 @@ async def fetch_historical_dataset(symbol: str, days: int) -> tuple[list[dict], "low": float(row[3]), "close": float(row[4]), "volume": float(row[5]), + "taker_buy_volume": float(row[9]) if len(row) > 9 else None, } for row in klines_raw ] @@ -89,6 +90,7 @@ async def fetch_historical_dataset(symbol: str, days: int) -> tuple[list[dict], "low": float(row[3]), "close": float(row[4]), "volume": float(row[5]), + "taker_buy_volume": float(row[9]) if len(row) > 9 else None, }) next_cursor = int(batch[-1][0]) + 900_000 if next_cursor <= cursor_ms or len(batch) < page_limit: diff --git a/frontend/dist/assets/AIAnalysisPanel-BbXTq8TV.js b/frontend/dist/assets/AIAnalysisPanel-BbXTq8TV.js deleted file mode 100644 index 67337d88f76d4ef9e2b43a7d4169b1a3621c828f..0000000000000000000000000000000000000000 --- a/frontend/dist/assets/AIAnalysisPanel-BbXTq8TV.js +++ /dev/null @@ -1,2 +0,0 @@ -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]); -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}; diff --git a/frontend/dist/assets/AIAnalysisPanel-DsgKGe3C.js b/frontend/dist/assets/AIAnalysisPanel-DsgKGe3C.js new file mode 100644 index 0000000000000000000000000000000000000000..c81b364f9e6eaa165647109f45a9bb0fe61a19e6 --- /dev/null +++ b/frontend/dist/assets/AIAnalysisPanel-DsgKGe3C.js @@ -0,0 +1,2 @@ +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]); +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}; diff --git a/frontend/dist/assets/AddPairModal-D8YkLLF_.js b/frontend/dist/assets/AddPairModal-D8YkLLF_.js deleted file mode 100644 index 4f25ba4daf9eba3a66b181879911186054d0b86d..0000000000000000000000000000000000000000 --- a/frontend/dist/assets/AddPairModal-D8YkLLF_.js +++ /dev/null @@ -1 +0,0 @@ -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}; diff --git a/frontend/dist/assets/AddPairModal-DCQtFcNW.js b/frontend/dist/assets/AddPairModal-DCQtFcNW.js new file mode 100644 index 0000000000000000000000000000000000000000..ab19e7654427b92bcd5fce1a676162c937a3fce7 --- /dev/null +++ b/frontend/dist/assets/AddPairModal-DCQtFcNW.js @@ -0,0 +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}; diff --git a/frontend/dist/assets/GlobalAISettingsModal-BOzCh0qM.js b/frontend/dist/assets/GlobalAISettingsModal-BOzCh0qM.js new file mode 100644 index 0000000000000000000000000000000000000000..93465cbca834c768174c07131aa8c1fe76a35d17 --- /dev/null +++ b/frontend/dist/assets/GlobalAISettingsModal-BOzCh0qM.js @@ -0,0 +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}; diff --git a/frontend/dist/assets/GlobalAISettingsModal-y_W5Q-P7.js b/frontend/dist/assets/GlobalAISettingsModal-y_W5Q-P7.js deleted file mode 100644 index 1ffd6ffcada8200f8b308d79a9761e93249f5872..0000000000000000000000000000000000000000 --- a/frontend/dist/assets/GlobalAISettingsModal-y_W5Q-P7.js +++ /dev/null @@ -1 +0,0 @@ -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}; diff --git a/frontend/dist/assets/ServerSettingsModal-B2vOj2j4.js b/frontend/dist/assets/ServerSettingsModal-B2vOj2j4.js new file mode 100644 index 0000000000000000000000000000000000000000..07b9f5d09c087d985d05905d9d3b9141695382f5 --- /dev/null +++ b/frontend/dist/assets/ServerSettingsModal-B2vOj2j4.js @@ -0,0 +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}; diff --git a/frontend/dist/assets/ServerSettingsModal-BJC6WDDG.js b/frontend/dist/assets/ServerSettingsModal-BJC6WDDG.js deleted file mode 100644 index 65844801fc5fd27066757472bbb893b63bcf7ae0..0000000000000000000000000000000000000000 --- a/frontend/dist/assets/ServerSettingsModal-BJC6WDDG.js +++ /dev/null @@ -1 +0,0 @@ -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}; diff --git a/frontend/dist/assets/index--kfpEFWJ.css b/frontend/dist/assets/index--kfpEFWJ.css deleted file mode 100644 index 3bc5384a768c651bb84fdd188f8d0bf9c7b8ad24..0000000000000000000000000000000000000000 --- a/frontend/dist/assets/index--kfpEFWJ.css +++ /dev/null @@ -1 +0,0 @@ -*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:JetBrains Mono,Fira Code,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}*{box-sizing:border-box;scrollbar-width:thin;scrollbar-color:#1f2937 transparent}*::-webkit-scrollbar{width:6px;height:6px}*::-webkit-scrollbar-track{background:transparent}*::-webkit-scrollbar-thumb{background-color:#1f2937;border-radius:3px}*::-webkit-scrollbar-thumb:hover{background-color:#374151}html,body{margin:0;padding:0;background-color:#0a0e1a;color:#f9fafb;font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif;min-height:100vh;-webkit-tap-highlight-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;overscroll-behavior-y:none}button,a,input,select,textarea{touch-action:manipulation}#root{min-height:100vh;display:flex;flex-direction:column}.container{width:100%}@media (min-width: 480px){.container{max-width:480px}}@media (min-width: 640px){.container{max-width:640px}}@media (min-width: 768px){.container{max-width:768px}}@media (min-width: 1024px){.container{max-width:1024px}}@media (min-width: 1280px){.container{max-width:1280px}}@media (min-width: 1536px){.container{max-width:1536px}}.skeleton{background:linear-gradient(90deg,#1f2937,#374151,#1f2937);background-size:200% 100%;animation:shimmer 1.5s infinite linear;border-radius:4px}.glow-long{box-shadow:0 0 15px #10b98126}.glow-short{box-shadow:0 0 15px #ef444426}.signal-card-container{content-visibility:auto;contain-intrinsic-size:1px 310px;will-change:transform}.card{border-radius:.75rem;border-width:1px;--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1));--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.input-field{border-radius:.5rem;border-width:1px;--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1));--tw-bg-opacity: 1;background-color:rgb(26 35 50 / var(--tw-bg-opacity, 1));padding:.5rem .75rem;font-size:.875rem;line-height:1.25rem;--tw-text-opacity: 1;color:rgb(249 250 251 / var(--tw-text-opacity, 1))}.input-field::-moz-placeholder{--tw-placeholder-opacity: 1;color:rgb(75 85 99 / var(--tw-placeholder-opacity, 1))}.input-field::placeholder{--tw-placeholder-opacity: 1;color:rgb(75 85 99 / var(--tw-placeholder-opacity, 1))}.input-field{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.input-field:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1));outline:2px solid transparent;outline-offset:2px;--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000);--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.no-scrollbar::-webkit-scrollbar{display:none}.no-scrollbar{-ms-overflow-style:none;scrollbar-width:none}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:0}.inset-y-0{top:0;bottom:0}.-bottom-1{bottom:-.25rem}.-right-1{right:-.25rem}.-right-2{right:-.5rem}.-top-0\.5{top:-.125rem}.-top-1{top:-.25rem}.bottom-0{bottom:0}.bottom-4{bottom:1rem}.left-0{left:0}.left-1\/2{left:50%}.left-2\.5{left:.625rem}.left-3{left:.75rem}.right-0{right:0}.right-2{right:.5rem}.right-2\.5{right:.625rem}.right-3{right:.75rem}.right-4{right:1rem}.top-0{top:0}.top-1\/2{top:50%}.top-2{top:.5rem}.top-full{top:100%}.z-10{z-index:10}.z-20{z-index:20}.z-40{z-index:40}.z-50{z-index:50}.z-\[100\]{z-index:100}.col-span-2{grid-column:span 2 / span 2}.m-auto{margin:auto}.mx-0\.5{margin-left:.125rem;margin-right:.125rem}.mx-3{margin-left:.75rem;margin-right:.75rem}.mx-auto{margin-left:auto;margin-right:auto}.my-0\.5{margin-top:.125rem;margin-bottom:.125rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.my-auto{margin-top:auto;margin-bottom:auto}.mb-0\.5{margin-bottom:.125rem}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.ml-1{margin-left:.25rem}.ml-2{margin-left:.5rem}.ml-4{margin-left:1rem}.mr-1\.5{margin-right:.375rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-2\.5{margin-top:.625rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.line-clamp-1{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-3{height:.75rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[185px\]{height:185px}.h-\[2px\]{height:2px}.h-\[34px\]{height:34px}.h-\[35vh\]{height:35vh}.h-\[40vh\]{height:40vh}.h-\[45vh\]{height:45vh}.h-\[55vh\]{height:55vh}.h-\[calc\(100vh-3\.5rem\)\]{height:calc(100vh - 3.5rem)}.h-full{height:100%}.h-screen{height:100vh}.max-h-60{max-height:15rem}.max-h-80{max-height:20rem}.max-h-\[420px\]{max-height:420px}.max-h-\[80vh\]{max-height:80vh}.max-h-\[92vh\]{max-height:92vh}.min-h-\[160px\]{min-height:160px}.min-h-\[170px\]{min-height:170px}.min-h-\[400px\]{min-height:400px}.min-h-\[420px\]{min-height:420px}.min-h-\[44px\]{min-height:44px}.min-h-\[50vh\]{min-height:50vh}.w-1{width:.25rem}.w-1\.5{width:.375rem}.w-10{width:2.5rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-20{width:5rem}.w-24{width:6rem}.w-28{width:7rem}.w-32{width:8rem}.w-4{width:1rem}.w-4\/5{width:80%}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-72{width:18rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-full{width:100%}.w-px{width:1px}.min-w-0{min-width:0px}.max-w-2xl{max-width:42rem}.max-w-4xl{max-width:56rem}.max-w-6xl{max-width:72rem}.max-w-\[100px\]{max-width:100px}.max-w-\[130px\]{max-width:130px}.max-w-\[70px\]{max-width:70px}.max-w-\[85\%\]{max-width:85%}.max-w-\[95\%\]{max-width:95%}.max-w-full{max-width:100%}.max-w-md{max-width:28rem}.max-w-sm{max-width:24rem}.max-w-xl{max-width:36rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-0{--tw-translate-y: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-2{--tw-translate-y: .5rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes bounce{0%,to{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}.animate-bounce{animation:bounce 1s infinite}@keyframes fade-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fade-in .3s ease-out}@keyframes ping{75%,to{transform:scale(2);opacity:0}}.animate-ping{animation:ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes pulse-green{0%,to{box-shadow:0 0 #10b98166}50%{box-shadow:0 0 0 8px #10b98100}}.animate-pulse-green{animation:pulse-green 2s infinite}@keyframes pulse-red{0%,to{box-shadow:0 0 #ef444466}50%{box-shadow:0 0 0 8px #ef444400}}.animate-pulse-red{animation:pulse-red 2s infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize{resize:both}.list-disc{list-style-type:disc}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.items-baseline{align-items:baseline}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.justify-around{justify-content:space-around}.gap-0\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-2\.5{gap:.625rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-2\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.625rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.625rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-3\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.875rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.875rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-border>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(31 41 55 / var(--tw-divide-opacity, 1))}.self-end{align-self:flex-end}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-normal{white-space:normal}.whitespace-nowrap{white-space:nowrap}.break-words{overflow-wrap:break-word}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.rounded-b-xl{border-bottom-right-radius:.75rem;border-bottom-left-radius:.75rem}.rounded-l-full{border-top-left-radius:9999px;border-bottom-left-radius:9999px}.rounded-r-full{border-top-right-radius:9999px;border-bottom-right-radius:9999px}.rounded-tl-sm{border-top-left-radius:.125rem}.rounded-tr-sm{border-top-right-radius:.125rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-accent-blue{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-accent-blue\/20{border-color:#3b82f633}.border-accent-blue\/30{border-color:#3b82f64d}.border-accent-blue\/40{border-color:#3b82f666}.border-accent-yellow\/20{border-color:#f59e0b33}.border-accent-yellow\/30{border-color:#f59e0b4d}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-amber-500\/20{border-color:#f59e0b33}.border-amber-500\/25{border-color:#f59e0b40}.border-amber-500\/30{border-color:#f59e0b4d}.border-amber-500\/35{border-color:#f59e0b59}.border-amber-500\/40{border-color:#f59e0b66}.border-border{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.border-border\/30{border-color:#1f29374d}.border-border\/40{border-color:#1f293766}.border-border\/50{border-color:#1f293780}.border-border\/60{border-color:#1f293799}.border-border\/70{border-color:#1f2937b3}.border-border\/80{border-color:#1f2937cc}.border-border\/90{border-color:#1f2937e6}.border-current{border-color:currentColor}.border-cyan-500\/30{border-color:#06b6d44d}.border-cyan-500\/35{border-color:#06b6d459}.border-cyan-500\/40{border-color:#06b6d466}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-emerald-500\/20{border-color:#10b98133}.border-emerald-500\/25{border-color:#10b98140}.border-emerald-500\/30{border-color:#10b9814d}.border-emerald-500\/40{border-color:#10b98166}.border-gray-400{--tw-border-opacity: 1;border-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.border-gray-500\/30{border-color:#6b72804d}.border-indigo-500\/35{border-color:#6366f159}.border-purple-500{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.border-purple-500\/20{border-color:#a855f733}.border-purple-500\/25{border-color:#a855f740}.border-purple-500\/30{border-color:#a855f74d}.border-purple-500\/40{border-color:#a855f766}.border-purple-500\/50{border-color:#a855f780}.border-red-500\/20{border-color:#ef444433}.border-red-500\/30{border-color:#ef44444d}.border-red-500\/40{border-color:#ef444466}.border-rose-500{--tw-border-opacity: 1;border-color:rgb(244 63 94 / var(--tw-border-opacity, 1))}.border-rose-500\/20{border-color:#f43f5e33}.border-rose-500\/25{border-color:#f43f5e40}.border-rose-500\/30{border-color:#f43f5e4d}.border-rose-500\/40{border-color:#f43f5e66}.border-signal-long{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-signal-long\/20{border-color:#10b98133}.border-signal-long\/30{border-color:#10b9814d}.border-signal-long\/40{border-color:#10b98166}.border-signal-short\/20{border-color:#ef444433}.border-signal-short\/30{border-color:#ef44444d}.border-signal-short\/40{border-color:#ef444466}.border-sky-500\/20{border-color:#0ea5e933}.border-sky-500\/40{border-color:#0ea5e966}.border-transparent{border-color:transparent}.border-t-purple-500{--tw-border-opacity: 1;border-top-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.border-t-transparent{border-top-color:transparent}.bg-\[\#090b0e\]{--tw-bg-opacity: 1;background-color:rgb(9 11 14 / var(--tw-bg-opacity, 1))}.bg-\[\#090b0e\]\/80{background-color:#090b0ecc}.bg-\[\#090b0e\]\/90{background-color:#090b0ee6}.bg-accent-blue{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-accent-blue\/10{background-color:#3b82f61a}.bg-accent-blue\/15{background-color:#3b82f626}.bg-accent-blue\/20{background-color:#3b82f633}.bg-accent-yellow{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-amber-400{--tw-bg-opacity: 1;background-color:rgb(251 191 36 / var(--tw-bg-opacity, 1))}.bg-amber-500\/10{background-color:#f59e0b1a}.bg-amber-500\/15{background-color:#f59e0b26}.bg-amber-500\/20{background-color:#f59e0b33}.bg-amber-600{--tw-bg-opacity: 1;background-color:rgb(217 119 6 / var(--tw-bg-opacity, 1))}.bg-amber-950\/15{background-color:#451a0326}.bg-amber-950\/20{background-color:#451a0333}.bg-bg-card{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-bg-card\/50{background-color:#11182780}.bg-bg-card\/70{background-color:#111827b3}.bg-bg-card\/80{background-color:#111827cc}.bg-bg-card\/90{background-color:#111827e6}.bg-bg-card\/95{background-color:#111827f2}.bg-bg-elevated{--tw-bg-opacity: 1;background-color:rgb(26 35 50 / var(--tw-bg-opacity, 1))}.bg-bg-elevated\/20{background-color:#1a233233}.bg-bg-elevated\/30{background-color:#1a23324d}.bg-bg-elevated\/40{background-color:#1a233266}.bg-bg-elevated\/50{background-color:#1a233280}.bg-bg-elevated\/60{background-color:#1a233299}.bg-bg-elevated\/70{background-color:#1a2332b3}.bg-bg-elevated\/80{background-color:#1a2332cc}.bg-bg-elevated\/90{background-color:#1a2332e6}.bg-bg-primary{--tw-bg-opacity: 1;background-color:rgb(10 14 26 / var(--tw-bg-opacity, 1))}.bg-bg-primary\/50{background-color:#0a0e1a80}.bg-bg-primary\/60{background-color:#0a0e1a99}.bg-bg-primary\/80{background-color:#0a0e1acc}.bg-bg-primary\/90{background-color:#0a0e1ae6}.bg-black\/80{background-color:#000c}.bg-blue-500\/10{background-color:#3b82f61a}.bg-cyan-400{--tw-bg-opacity: 1;background-color:rgb(34 211 238 / var(--tw-bg-opacity, 1))}.bg-cyan-500\/15{background-color:#06b6d426}.bg-cyan-500\/20{background-color:#06b6d433}.bg-cyan-950\/15{background-color:#08334426}.bg-emerald-400{--tw-bg-opacity: 1;background-color:rgb(52 211 153 / var(--tw-bg-opacity, 1))}.bg-emerald-500{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.bg-emerald-500\/10{background-color:#10b9811a}.bg-emerald-500\/15{background-color:#10b98126}.bg-emerald-500\/20{background-color:#10b98133}.bg-emerald-500\/30{background-color:#10b9814d}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.bg-emerald-950\/15{background-color:#022c2226}.bg-gray-500{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.bg-gray-500\/10{background-color:#6b72801a}.bg-gray-500\/15{background-color:#6b728026}.bg-gray-500\/20{background-color:#6b728033}.bg-gray-500\/30{background-color:#6b72804d}.bg-indigo-500\/15{background-color:#6366f126}.bg-purple-400{--tw-bg-opacity: 1;background-color:rgb(192 132 252 / var(--tw-bg-opacity, 1))}.bg-purple-500\/10{background-color:#a855f71a}.bg-purple-500\/15{background-color:#a855f726}.bg-purple-500\/20{background-color:#a855f733}.bg-purple-500\/25{background-color:#a855f740}.bg-purple-500\/30{background-color:#a855f74d}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-purple-600\/15{background-color:#9333ea26}.bg-purple-600\/20{background-color:#9333ea33}.bg-purple-600\/30{background-color:#9333ea4d}.bg-purple-950\/15{background-color:#3b076426}.bg-purple-950\/20{background-color:#3b076433}.bg-purple-950\/30{background-color:#3b07644d}.bg-red-500\/10{background-color:#ef44441a}.bg-red-500\/20{background-color:#ef444433}.bg-red-950\/40{background-color:#450a0a66}.bg-rose-400{--tw-bg-opacity: 1;background-color:rgb(251 113 133 / var(--tw-bg-opacity, 1))}.bg-rose-500{--tw-bg-opacity: 1;background-color:rgb(244 63 94 / var(--tw-bg-opacity, 1))}.bg-rose-500\/10{background-color:#f43f5e1a}.bg-rose-500\/15{background-color:#f43f5e26}.bg-rose-500\/20{background-color:#f43f5e33}.bg-rose-500\/30{background-color:#f43f5e4d}.bg-rose-600{--tw-bg-opacity: 1;background-color:rgb(225 29 72 / var(--tw-bg-opacity, 1))}.bg-rose-950\/15{background-color:#4c051926}.bg-rose-950\/60{background-color:#4c051999}.bg-signal-long{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.bg-signal-long-bg,.bg-signal-long\/10{background-color:#10b9811a}.bg-signal-long\/15{background-color:#10b98126}.bg-signal-long\/20{background-color:#10b98133}.bg-signal-neutral-bg{background-color:#6b72801a}.bg-signal-short{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-signal-short-bg,.bg-signal-short\/10{background-color:#ef44441a}.bg-signal-short\/15{background-color:#ef444426}.bg-signal-short\/20{background-color:#ef444433}.bg-sky-400{--tw-bg-opacity: 1;background-color:rgb(56 189 248 / var(--tw-bg-opacity, 1))}.bg-sky-500\/10{background-color:#0ea5e91a}.bg-sky-500\/15{background-color:#0ea5e926}.bg-sky-600{--tw-bg-opacity: 1;background-color:rgb(2 132 199 / var(--tw-bg-opacity, 1))}.bg-text-muted{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.bg-text-muted\/30{background-color:#4b55634d}.bg-text-muted\/40{background-color:#4b556366}.bg-transparent{background-color:transparent}.bg-yellow-500\/10{background-color:#eab3081a}.bg-gradient-to-b{background-image:linear-gradient(to bottom,var(--tw-gradient-stops))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-amber-500{--tw-gradient-from: #f59e0b var(--tw-gradient-from-position);--tw-gradient-to: rgb(245 158 11 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-amber-950\/20{--tw-gradient-from: rgb(69 26 3 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(69 26 3 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-cyan-950\/20{--tw-gradient-from: rgb(8 51 68 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(8 51 68 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-emerald-500{--tw-gradient-from: #10b981 var(--tw-gradient-from-position);--tw-gradient-to: rgb(16 185 129 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-emerald-950\/25{--tw-gradient-from: rgb(2 44 34 / .25) var(--tw-gradient-from-position);--tw-gradient-to: rgb(2 44 34 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-500{--tw-gradient-from: #6b7280 var(--tw-gradient-from-position);--tw-gradient-to: rgb(107 114 128 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-orange-500{--tw-gradient-from: #f97316 var(--tw-gradient-from-position);--tw-gradient-to: rgb(249 115 22 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-500\/20{--tw-gradient-from: rgb(168 85 247 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-600{--tw-gradient-from: #9333ea var(--tw-gradient-from-position);--tw-gradient-to: rgb(147 51 234 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-950\/40{--tw-gradient-from: rgb(59 7 100 / .4) var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 7 100 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-500{--tw-gradient-from: #ef4444 var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 68 68 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-rose-950\/20{--tw-gradient-from: rgb(76 5 25 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(76 5 25 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-rose-950\/25{--tw-gradient-from: rgb(76 5 25 / .25) var(--tw-gradient-from-position);--tw-gradient-to: rgb(76 5 25 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-signal-long\/10{--tw-gradient-from: rgb(16 185 129 / .1) var(--tw-gradient-from-position);--tw-gradient-to: rgb(16 185 129 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-signal-short\/10{--tw-gradient-from: rgb(239 68 68 / .1) var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 68 68 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-transparent{--tw-gradient-from: transparent var(--tw-gradient-from-position);--tw-gradient-to: rgb(0 0 0 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-yellow-500{--tw-gradient-from: #eab308 var(--tw-gradient-from-position);--tw-gradient-to: rgb(234 179 8 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-bg-card{--tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #111827 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-bg-elevated\/40{--tw-gradient-to: rgb(26 35 50 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(26 35 50 / .4) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-purple-500{--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #a855f7 var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-amber-400{--tw-gradient-to: #fbbf24 var(--tw-gradient-to-position)}.to-amber-600{--tw-gradient-to: #d97706 var(--tw-gradient-to-position)}.to-bg-card{--tw-gradient-to: #111827 var(--tw-gradient-to-position)}.to-blue-500\/20{--tw-gradient-to: rgb(59 130 246 / .2) var(--tw-gradient-to-position)}.to-gray-400{--tw-gradient-to: #9ca3af var(--tw-gradient-to-position)}.to-green-400{--tw-gradient-to: #4ade80 var(--tw-gradient-to-position)}.to-indigo-600{--tw-gradient-to: #4f46e5 var(--tw-gradient-to-position)}.to-purple-950\/20{--tw-gradient-to: rgb(59 7 100 / .2) var(--tw-gradient-to-position)}.to-rose-400{--tw-gradient-to: #fb7185 var(--tw-gradient-to-position)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.fill-black{fill:#000}.fill-yellow-300{fill:#fde047}.p-0\.5{padding:.125rem}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-3{padding:.75rem}.p-3\.5{padding:.875rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.px-0{padding-left:0;padding-right:0}.px-0\.5{padding-left:.125rem;padding-right:.125rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-3\.5{padding-left:.875rem;padding-right:.875rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-3\.5{padding-top:.875rem;padding-bottom:.875rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-1{padding-bottom:.25rem}.pb-1\.5{padding-bottom:.375rem}.pb-16{padding-bottom:4rem}.pb-2{padding-bottom:.5rem}.pb-2\.5{padding-bottom:.625rem}.pb-20{padding-bottom:5rem}.pb-3{padding-bottom:.75rem}.pb-\[max\(0\.35rem\,env\(safe-area-inset-bottom\)\)\]{padding-bottom:max(.35rem,env(safe-area-inset-bottom))}.pl-3{padding-left:.75rem}.pl-4{padding-left:1rem}.pl-7{padding-left:1.75rem}.pl-8{padding-left:2rem}.pl-9{padding-left:2.25rem}.pr-1{padding-right:.25rem}.pr-10{padding-right:2.5rem}.pr-16{padding-right:4rem}.pr-2{padding-right:.5rem}.pr-2\.5{padding-right:.625rem}.pr-3{padding-right:.75rem}.pr-8{padding-right:2rem}.pr-9{padding-right:2.25rem}.pt-0\.5{padding-top:.125rem}.pt-1{padding-top:.25rem}.pt-2{padding-top:.5rem}.pt-2\.5{padding-top:.625rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.align-bottom{vertical-align:bottom}.font-mono{font-family:JetBrains Mono,Fira Code,monospace}.font-sans{font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"}.text-\[10\.5px\]{font-size:10.5px}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[8px\]{font-size:8px}.text-\[9px\]{font-size:9px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.capitalize{text-transform:capitalize}.italic{font-style:italic}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.leading-snug{line-height:1.375}.leading-tight{line-height:1.25}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-accent-blue{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-accent-blue\/80{color:#3b82f6cc}.text-accent-blue\/90{color:#3b82f6e6}.text-accent-yellow{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity, 1))}.text-amber-100\/90{color:#fef3c7e6}.text-amber-200{--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity, 1))}.text-amber-200\/80{color:#fde68acc}.text-amber-300{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.text-amber-300\/80{color:#fcd34dcc}.text-amber-300\/90{color:#fcd34de6}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-amber-400\/90{color:#fbbf24e6}.text-bg-primary{--tw-text-opacity: 1;color:rgb(10 14 26 / var(--tw-text-opacity, 1))}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.text-border{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-cyan-300{--tw-text-opacity: 1;color:rgb(103 232 249 / var(--tw-text-opacity, 1))}.text-cyan-400{--tw-text-opacity: 1;color:rgb(34 211 238 / var(--tw-text-opacity, 1))}.text-emerald-200{--tw-text-opacity: 1;color:rgb(167 243 208 / var(--tw-text-opacity, 1))}.text-emerald-300{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.text-emerald-300\/70{color:#6ee7b7b3}.text-emerald-300\/80{color:#6ee7b7cc}.text-emerald-300\/90{color:#6ee7b7e6}.text-emerald-400{--tw-text-opacity: 1;color:rgb(52 211 153 / var(--tw-text-opacity, 1))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-indigo-300{--tw-text-opacity: 1;color:rgb(165 180 252 / var(--tw-text-opacity, 1))}.text-orange-400{--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.text-purple-100{--tw-text-opacity: 1;color:rgb(243 232 255 / var(--tw-text-opacity, 1))}.text-purple-200{--tw-text-opacity: 1;color:rgb(233 213 255 / var(--tw-text-opacity, 1))}.text-purple-200\/80{color:#e9d5ffcc}.text-purple-200\/90{color:#e9d5ffe6}.text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.text-purple-300\/80{color:#d8b4fecc}.text-purple-300\/90{color:#d8b4fee6}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-red-100{--tw-text-opacity: 1;color:rgb(254 226 226 / var(--tw-text-opacity, 1))}.text-red-200{--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.text-red-200\/90{color:#fecacae6}.text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-400\/80{color:#f87171cc}.text-rose-100{--tw-text-opacity: 1;color:rgb(255 228 230 / var(--tw-text-opacity, 1))}.text-rose-200{--tw-text-opacity: 1;color:rgb(254 205 211 / var(--tw-text-opacity, 1))}.text-rose-200\/80{color:#fecdd3cc}.text-rose-200\/90{color:#fecdd3e6}.text-rose-300{--tw-text-opacity: 1;color:rgb(253 164 175 / var(--tw-text-opacity, 1))}.text-rose-300\/70{color:#fda4afb3}.text-rose-300\/80{color:#fda4afcc}.text-rose-400{--tw-text-opacity: 1;color:rgb(251 113 133 / var(--tw-text-opacity, 1))}.text-signal-long{--tw-text-opacity: 1;color:rgb(16 185 129 / var(--tw-text-opacity, 1))}.text-signal-long\/80{color:#10b981cc}.text-signal-long\/90{color:#10b981e6}.text-signal-short{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-sky-300{--tw-text-opacity: 1;color:rgb(125 211 252 / var(--tw-text-opacity, 1))}.text-sky-400{--tw-text-opacity: 1;color:rgb(56 189 248 / var(--tw-text-opacity, 1))}.text-text-muted{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-text-muted\/40{color:#4b556366}.text-text-muted\/70{color:#4b5563b3}.text-text-primary{--tw-text-opacity: 1;color:rgb(249 250 251 / var(--tw-text-opacity, 1))}.text-text-primary\/95{color:#f9fafbf2}.text-text-secondary{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-text-secondary\/70{color:#6b7280b3}.text-text-secondary\/80{color:#6b7280cc}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-300{--tw-text-opacity: 1;color:rgb(253 224 71 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.underline{text-decoration-line:underline}.accent-emerald-500{accent-color:#10b981}.accent-purple-500{accent-color:#a855f7}.opacity-0{opacity:0}.opacity-100{opacity:1}.opacity-50{opacity:.5}.opacity-70{opacity:.7}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_25px_rgba\(16\,185\,129\,0\.12\)\]{--tw-shadow: 0 0 25px rgba(16,185,129,.12);--tw-shadow-colored: 0 0 25px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_25px_rgba\(239\,68\,68\,0\.12\)\]{--tw-shadow: 0 0 25px rgba(239,68,68,.12);--tw-shadow-colored: 0 0 25px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 rgb(0 0 0 / .05);--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-accent-blue\/30{--tw-shadow-color: rgb(59 130 246 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-amber-400\/50{--tw-shadow-color: rgb(251 191 36 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-amber-500\/20{--tw-shadow-color: rgb(245 158 11 / .2);--tw-shadow: var(--tw-shadow-colored)}.shadow-amber-950\/30{--tw-shadow-color: rgb(69 26 3 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-cyan-400\/50{--tw-shadow-color: rgb(34 211 238 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-cyan-950\/30{--tw-shadow-color: rgb(8 51 68 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-emerald-400\/50{--tw-shadow-color: rgb(52 211 153 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-emerald-600\/30{--tw-shadow-color: rgb(5 150 105 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-emerald-950\/30{--tw-shadow-color: rgb(2 44 34 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-emerald-950\/40{--tw-shadow-color: rgb(2 44 34 / .4);--tw-shadow: var(--tw-shadow-colored)}.shadow-purple-500\/10{--tw-shadow-color: rgb(168 85 247 / .1);--tw-shadow: var(--tw-shadow-colored)}.shadow-purple-500\/20{--tw-shadow-color: rgb(168 85 247 / .2);--tw-shadow: var(--tw-shadow-colored)}.shadow-purple-500\/25{--tw-shadow-color: rgb(168 85 247 / .25);--tw-shadow: var(--tw-shadow-colored)}.shadow-purple-600\/10{--tw-shadow-color: rgb(147 51 234 / .1);--tw-shadow: var(--tw-shadow-colored)}.shadow-purple-600\/25{--tw-shadow-color: rgb(147 51 234 / .25);--tw-shadow: var(--tw-shadow-colored)}.shadow-purple-600\/30{--tw-shadow-color: rgb(147 51 234 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-rose-400\/50{--tw-shadow-color: rgb(251 113 133 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-rose-950\/30{--tw-shadow-color: rgb(76 5 25 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-rose-950\/40{--tw-shadow-color: rgb(76 5 25 / .4);--tw-shadow: var(--tw-shadow-colored)}.shadow-signal-long\/50{--tw-shadow-color: rgb(16 185 129 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-signal-short\/50{--tw-shadow-color: rgb(239 68 68 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-sky-600\/30{--tw-shadow-color: rgb(2 132 199 / .3);--tw-shadow: var(--tw-shadow-colored)}.outline-none{outline:2px solid transparent;outline-offset:2px}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-accent-blue{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.ring-accent-blue\/50{--tw-ring-color: rgb(59 130 246 / .5)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur{--tw-backdrop-blur: blur(8px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-xl{--tw-backdrop-blur: blur(24px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-150{transition-duration:.15s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.duration-700{transition-duration:.7s}.ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}.marker\:text-accent-blue *::marker{color:#3b82f6}.marker\:text-accent-blue::marker{color:#3b82f6}.placeholder\:text-text-muted::-moz-placeholder{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.placeholder\:text-text-muted::placeholder{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:border-accent-blue:hover{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.hover\:border-accent-blue\/40:hover{border-color:#3b82f666}.hover\:border-accent-blue\/50:hover{border-color:#3b82f680}.hover\:border-amber-500\/50:hover{border-color:#f59e0b80}.hover\:border-border:hover{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.hover\:border-border\/80:hover{border-color:#1f2937cc}.hover\:border-cyan-500\/60:hover{border-color:#06b6d499}.hover\:border-emerald-500\/50:hover{border-color:#10b98180}.hover\:border-emerald-500\/60:hover{border-color:#10b98199}.hover\:border-purple-400:hover{--tw-border-opacity: 1;border-color:rgb(192 132 252 / var(--tw-border-opacity, 1))}.hover\:border-purple-500\/40:hover{border-color:#a855f766}.hover\:border-purple-500\/50:hover{border-color:#a855f780}.hover\:border-rose-500\/60:hover{border-color:#f43f5e99}.hover\:border-signal-long\/60:hover{border-color:#10b98199}.hover\:border-signal-short\/60:hover{border-color:#ef444499}.hover\:border-sky-400:hover{--tw-border-opacity: 1;border-color:rgb(56 189 248 / var(--tw-border-opacity, 1))}.hover\:border-text-secondary:hover{--tw-border-opacity: 1;border-color:rgb(107 114 128 / var(--tw-border-opacity, 1))}.hover\:bg-accent-blue\/20:hover{background-color:#3b82f633}.hover\:bg-accent-blue\/90:hover{background-color:#3b82f6e6}.hover\:bg-amber-500:hover{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.hover\:bg-amber-500\/20:hover{background-color:#f59e0b33}.hover\:bg-amber-500\/25:hover{background-color:#f59e0b40}.hover\:bg-bg-card:hover{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.hover\:bg-bg-elevated:hover{--tw-bg-opacity: 1;background-color:rgb(26 35 50 / var(--tw-bg-opacity, 1))}.hover\:bg-bg-elevated\/70:hover{background-color:#1a2332b3}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-border:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-500:hover{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-500\/20:hover{background-color:#10b98133}.hover\:bg-gray-500\/20:hover{background-color:#6b728033}.hover\:bg-purple-500:hover{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.hover\:bg-purple-500\/20:hover{background-color:#a855f733}.hover\:bg-purple-600\/20:hover{background-color:#9333ea33}.hover\:bg-purple-600\/30:hover{background-color:#9333ea4d}.hover\:bg-purple-600\/50:hover{background-color:#9333ea80}.hover\:bg-purple-950\/40:hover{background-color:#3b076466}.hover\:bg-red-500\/20:hover{background-color:#ef444433}.hover\:bg-red-500\/30:hover{background-color:#ef44444d}.hover\:bg-rose-500:hover{--tw-bg-opacity: 1;background-color:rgb(244 63 94 / var(--tw-bg-opacity, 1))}.hover\:bg-rose-500\/20:hover{background-color:#f43f5e33}.hover\:bg-signal-long-bg:hover{background-color:#10b9811a}.hover\:bg-signal-short-bg:hover{background-color:#ef44441a}.hover\:bg-sky-500\/25:hover{background-color:#0ea5e940}.hover\:from-amber-400:hover{--tw-gradient-from: #fbbf24 var(--tw-gradient-from-position);--tw-gradient-to: rgb(251 191 36 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:from-purple-500:hover{--tw-gradient-from: #a855f7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:from-purple-500\/30:hover{--tw-gradient-from: rgb(168 85 247 / .3) var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:to-amber-500:hover{--tw-gradient-to: #f59e0b var(--tw-gradient-to-position)}.hover\:to-blue-500\/30:hover{--tw-gradient-to: rgb(59 130 246 / .3) var(--tw-gradient-to-position)}.hover\:to-indigo-500:hover{--tw-gradient-to: #6366f1 var(--tw-gradient-to-position)}.hover\:text-amber-300:hover{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.hover\:text-amber-400:hover{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.hover\:text-emerald-300:hover{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.hover\:text-emerald-400:hover{--tw-text-opacity: 1;color:rgb(52 211 153 / var(--tw-text-opacity, 1))}.hover\:text-purple-200:hover{--tw-text-opacity: 1;color:rgb(233 213 255 / var(--tw-text-opacity, 1))}.hover\:text-purple-300:hover{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.hover\:text-red-300:hover{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.hover\:text-rose-200:hover{--tw-text-opacity: 1;color:rgb(254 205 211 / var(--tw-text-opacity, 1))}.hover\:text-rose-400:hover{--tw-text-opacity: 1;color:rgb(251 113 133 / var(--tw-text-opacity, 1))}.hover\:text-signal-long:hover{--tw-text-opacity: 1;color:rgb(16 185 129 / var(--tw-text-opacity, 1))}.hover\:text-signal-short:hover{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.hover\:text-sky-300:hover{--tw-text-opacity: 1;color:rgb(125 211 252 / var(--tw-text-opacity, 1))}.hover\:text-text-primary:hover{--tw-text-opacity: 1;color:rgb(249 250 251 / var(--tw-text-opacity, 1))}.hover\:text-text-secondary:hover{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-90:hover{opacity:.9}.focus\:border-accent-blue:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\:border-amber-400:focus{--tw-border-opacity: 1;border-color:rgb(251 191 36 / var(--tw-border-opacity, 1))}.focus\:border-emerald-400:focus{--tw-border-opacity: 1;border-color:rgb(52 211 153 / var(--tw-border-opacity, 1))}.focus\:border-purple-400:focus{--tw-border-opacity: 1;border-color:rgb(192 132 252 / var(--tw-border-opacity, 1))}.focus\:border-purple-500:focus{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.focus\:border-purple-500\/50:focus{border-color:#a855f780}.focus\:border-purple-500\/60:focus{border-color:#a855f799}.focus\:border-rose-400:focus{--tw-border-opacity: 1;border-color:rgb(251 113 133 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-accent-blue:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.focus\:ring-amber-400:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(251 191 36 / var(--tw-ring-opacity, 1))}.active\:scale-90:active{--tw-scale-x: .9;--tw-scale-y: .9;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.active\:scale-95:active{--tw-scale-x: .95;--tw-scale-y: .95;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.group:hover .group-hover\:scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}@media (min-width: 480px){.xs\:inline{display:inline}.xs\:hidden{display:none}.xs\:max-w-\[100px\]{max-width:100px}.xs\:max-w-\[170px\]{max-width:170px}.xs\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width: 640px){.sm\:left-auto{left:auto}.sm\:col-span-1{grid-column:span 1 / span 1}.sm\:col-span-3{grid-column:span 3 / span 3}.sm\:mx-5{margin-left:1.25rem;margin-right:1.25rem}.sm\:mb-5{margin-bottom:1.25rem}.sm\:mb-6{margin-bottom:1.5rem}.sm\:inline{display:inline}.sm\:flex{display:flex}.sm\:hidden{display:none}.sm\:w-32{width:8rem}.sm\:w-60{width:15rem}.sm\:w-80{width:20rem}.sm\:w-auto{width:auto}.sm\:max-w-\[120px\]{max-width:120px}.sm\:max-w-\[220px\]{max-width:220px}.sm\:max-w-\[75\%\]{max-width:75%}.sm\:max-w-\[90\%\]{max-width:90%}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-2{gap:.5rem}.sm\:gap-2\.5{gap:.625rem}.sm\:gap-3{gap:.75rem}.sm\:gap-4{gap:1rem}.sm\:self-auto{align-self:auto}.sm\:border-r{border-right-width:1px}.sm\:border-border{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.sm\:bg-transparent{background-color:transparent}.sm\:p-0{padding:0}.sm\:p-3{padding:.75rem}.sm\:p-3\.5{padding:.875rem}.sm\:p-4{padding:1rem}.sm\:p-5{padding:1.25rem}.sm\:p-6{padding:1.5rem}.sm\:px-2{padding-left:.5rem;padding-right:.5rem}.sm\:px-3{padding-left:.75rem;padding-right:.75rem}.sm\:px-3\.5{padding-left:.875rem;padding-right:.875rem}.sm\:px-5{padding-left:1.25rem;padding-right:1.25rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.sm\:py-4{padding-top:1rem;padding-bottom:1rem}.sm\:py-5{padding-top:1.25rem;padding-bottom:1.25rem}.sm\:text-left{text-align:left}.sm\:text-2xl{font-size:1.5rem;line-height:2rem}.sm\:text-\[10px\]{font-size:10px}.sm\:text-\[11px\]{font-size:11px}.sm\:text-\[12px\]{font-size:12px}.sm\:text-\[13px\]{font-size:13px}.sm\:text-\[9px\]{font-size:9px}.sm\:text-base{font-size:1rem;line-height:1.5rem}.sm\:text-lg{font-size:1.125rem;line-height:1.75rem}.sm\:text-sm{font-size:.875rem;line-height:1.25rem}.sm\:text-xs{font-size:.75rem;line-height:1rem}.sm\:opacity-0{opacity:0}.group:hover .sm\:group-hover\:opacity-100{opacity:1}}@media (min-width: 768px){.md\:inline{display:inline}.md\:flex{display:flex}.md\:hidden{display:none}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:pb-4{padding-bottom:1rem}.md\:pb-5{padding-bottom:1.25rem}}@media (min-width: 1024px){.lg\:inline{display:inline}.lg\:flex{display:flex}.lg\:w-72{width:18rem}.lg\:w-80{width:20rem}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:flex-row{flex-direction:row}.lg\:items-center{align-items:center}.lg\:border-l{border-left-width:1px}.lg\:border-t-0{border-top-width:0px}}@media (min-width: 1280px){.xl\:w-80{width:20rem}.xl\:w-96{width:24rem}.xl\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}} diff --git a/frontend/dist/assets/index-CaCGPr1l.js b/frontend/dist/assets/index-CaCGPr1l.js new file mode 100644 index 0000000000000000000000000000000000000000..ccc48ac087a9dcc52651c1e7ff217d7aab03312d --- /dev/null +++ b/frontend/dist/assets/index-CaCGPr1l.js @@ -0,0 +1,45 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AddPairModal-DCQtFcNW.js","assets/vendor-query-BSPl6-aq.js","assets/vendor-icons-BBZkXbgm.js","assets/vendor-react-BnvheTds.js","assets/AIAnalysisPanel-DsgKGe3C.js","assets/GlobalAISettingsModal-BOzCh0qM.js","assets/ServerSettingsModal-B2vOj2j4.js"])))=>i.map(i=>d[i]); +import{j as r,u as as,a as os,b as Zt,r as y,Q as Lo,c as Ao,R as Oo}from"./vendor-query-BSPl6-aq.js";import{r as zo}from"./vendor-react-BnvheTds.js";import{M as ia,T as Ct,a as Je,X as Et,I as Io,C as or,b as ra,B as na,P as lr,L as Xs,S as Zs,c as Xe,d as ve,e as Tt,Z as Oe,f as at,g as es,h as Fs,i as ot,j as Fe,R as Pe,k as Us,l as _t,m as Be,n as $o,F as ts,A as Do,o as aa,p as oa,q as Bo,K as Fo,r as Uo,s as Qt,W as qo,t as Rt,u as Wo,v as Ho,w as cr,x as Vo,y as Ko,z as Go,D as wt,E as dr,G as ei,H as Qo,J as Pr,N as Yo,O as Jo,Q as Xo,U as Zo,V as el,Y as tl,_ as sl,$ as la,a0 as il}from"./vendor-icons-BBZkXbgm.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))i(n);new MutationObserver(n=>{for(const a of n)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(n){const a={};return n.integrity&&(a.integrity=n.integrity),n.referrerPolicy&&(a.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?a.credentials="include":n.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(n){if(n.ep)return;n.ep=!0;const a=t(n);fetch(n.href,a)}})();var Ki={},Lr=zo;Ki.createRoot=Lr.createRoot,Ki.hydrateRoot=Lr.hydrateRoot;const rl="modulepreload",nl=function(s){return"/"+s},Ar={},xt=function(e,t,i){let n=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");n=Promise.allSettled(t.map(c=>{if(c=nl(c),c in Ar)return;Ar[c]=!0;const d=c.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${h}`))return;const u=document.createElement("link");if(u.rel=d?"stylesheet":rl,d||(u.as="script"),u.crossOrigin="",u.href=c,l&&u.setAttribute("nonce",l),document.head.appendChild(u),d)return new Promise((m,x)=>{u.addEventListener("load",m),u.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${c}`)))})}))}function a(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return n.then(o=>{for(const l of o||[])l.status==="rejected"&&a(l.reason);return e().catch(a)})},Or={LONG:{label:"LONG",icon:r.jsx(Je,{size:14,strokeWidth:2.5}),classes:"bg-signal-long-bg text-signal-long border border-signal-long/40"},SHORT:{label:"SHORT",icon:r.jsx(Ct,{size:14,strokeWidth:2.5}),classes:"bg-signal-short-bg text-signal-short border border-signal-short/40"},NEUTRAL:{label:"NEUTRAL",icon:r.jsx(ia,{size:14,strokeWidth:2.5}),classes:"bg-signal-neutral-bg text-text-secondary border border-border"}},al={sm:"text-xs px-2 py-0.5 gap-1",md:"text-sm px-2.5 py-1 gap-1.5",lg:"text-base px-3 py-1.5 gap-2"};function hr({direction:s,size:e="md"}){const{label:t,icon:i,classes:n}=Or[s]||Or.NEUTRAL;return r.jsxs("span",{className:`inline-flex items-center font-mono font-bold rounded-md ${n} ${al[e]}`,children:[i,t]})}function ca(s,e){return function(){return s.apply(e,arguments)}}const{toString:ol}=Object.prototype,{getPrototypeOf:Ze}=Object,{iterator:ls,toStringTag:da}=Symbol,ss=(({hasOwnProperty:s})=>(e,t)=>s.call(e,t))(Object.prototype),ha=s=>typeof s=="string"&&(s==="__proto__"||s==="constructor"||s==="prototype"),ua=(s,e,t)=>s===Object.prototype||!t&&e===null,ll=s=>{if(!Object.isExtensible(s))return!1;const e=Object.getOwnPropertyNames(s);return Object.getOwnPropertySymbols&&e.push(...Object.getOwnPropertySymbols(s)),e.every(t=>{if(ha(t))return!1;const i=Object.getOwnPropertyDescriptor(s,t);return!!i&&i.configurable&&i.writable===!0})},is=(s,e)=>{let t=s;const i=[];for(;t!=null;){if(i.indexOf(t)!==-1)return!1;i.push(t);const n=Ze(t);if(ua(t,n,t===s))return!1;if(ss(t,e))return!0;t=n}return!1},cl=(s,e)=>s!=null&&is(s,e)?s[e]:void 0,dl=s=>{if(s==null||typeof s!="object"&&typeof s!="function")return s;const e=Ze(s);if(e===null&&ll(s))return s;const t=Object.create(null),i=Object.create(null),n=[];let a=s;for(;a!=null&&n.indexOf(a)===-1;){n.push(a);const o=a===s?e:Ze(a);if(ua(a,o,a===s))break;const l=Object.getOwnPropertyNames(a);Object.getOwnPropertySymbols&&l.push(...Object.getOwnPropertySymbols(a));for(const c of l)ha(c)||ss(i,c)||(t[c]=s[c],i[c]=!0);a=o}return t},ur=(s=>e=>{const t=ol.call(e);return s[t]||(s[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),Ce=s=>(s=s.toLowerCase(),e=>ur(e)===s),ti=s=>e=>typeof e===s,{isArray:lt}=Array,ct=ti("undefined");function zt(s){return s!==null&&!ct(s)&&s.constructor!==null&&!ct(s.constructor)&&je(s.constructor.isBuffer)&&s.constructor.isBuffer(s)}const ma=Ce("ArrayBuffer");function hl(s){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(s):e=s&&s.buffer&&ma(s.buffer),e}const ul=ti("string"),je=ti("function"),pa=ti("number"),It=s=>s!==null&&typeof s=="object",ml=s=>s===!0||s===!1,Ls=s=>{if(!It(s))return!1;const e=Ze(s);return(e===null||e===Object.prototype||Ze(e)===null)&&!is(s,da)&&!is(s,ls)},pl=s=>{if(!It(s)||zt(s))return!1;try{return Object.keys(s).length===0&&Object.getPrototypeOf(s)===Object.prototype}catch{return!1}},fl=Ce("Date"),xl=Ce("File"),bl=s=>!!(s&&typeof s.uri<"u"),gl=s=>s&&typeof s.getParts<"u",vl=Ce("Blob"),yl=Ce("FileList"),wl=Ce("Set"),Nl=s=>It(s)&&je(s.pipe);function jl(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const zr=jl(),Ir=typeof zr.FormData<"u"?zr.FormData:void 0,_l=s=>{if(!s)return!1;if(Ir&&s instanceof Ir)return!0;const e=Ze(s);if(!e||e===Object.prototype||!je(s.append))return!1;const t=ur(s);return t==="formdata"||t==="object"&&je(s.toString)&&s.toString()==="[object FormData]"},Sl=Ce("URLSearchParams"),[kl,Ml,Cl,El]=["ReadableStream","Request","Response","Headers"].map(Ce),Tl=s=>s.trim?s.trim():s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function cs(s,e,{allOwnKeys:t=!1}={}){if(s===null||typeof s>"u")return;let i,n;if(typeof s!="object"&&(s=[s]),lt(s))for(i=0,n=s.length;i0;)if(n=t[i],e===n.toLowerCase())return n;return null}const it=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,xa=s=>!ct(s)&&s!==it;function Gi(...s){const{caseless:e,skipUndefined:t}=xa(this)&&this||{},i={},n=(a,o)=>{if(o==="__proto__"||o==="constructor"||o==="prototype")return;const l=e&&typeof o=="string"&&fa(i,o)||o,c=ss(i,l)?i[l]:void 0;Ls(c)&&Ls(a)?i[l]=Gi(c,a):Ls(a)?i[l]=Gi({},a):lt(a)?i[l]=a.slice():(!t||!ct(a))&&(i[l]=a)};for(let a=0,o=s.length;a(cs(e,(n,a)=>{t&&je(n)?Object.defineProperty(s,a,{__proto__:null,value:ca(n,t),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(s,a,{__proto__:null,value:n,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:i}),s),Pl=s=>(s.charCodeAt(0)===65279&&(s=s.slice(1)),s),Ll=(s,e,t,i)=>{s.prototype=Object.create(e.prototype,i),Object.defineProperty(s.prototype,"constructor",{__proto__:null,value:s,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(s,"super",{__proto__:null,value:e.prototype}),t&&Object.assign(s.prototype,t)},Al=(s,e,t,i)=>{let n,a,o;const l={};if(e=e||{},s==null)return e;do{for(n=Object.getOwnPropertyNames(s),a=n.length;a-- >0;)o=n[a],(!i||i(o,s,e))&&!l[o]&&(e[o]=s[o],l[o]=!0);s=t!==!1&&Ze(s)}while(s&&(!t||t(s,e))&&s!==Object.prototype);return e},Ol=(s,e,t)=>{s=String(s),(t===void 0||t>s.length)&&(t=s.length),t-=e.length;const i=s.indexOf(e,t);return i!==-1&&i===t},zl=s=>{if(!s)return null;if(lt(s))return s;let e=s.length;if(!pa(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=s[e];return t},Il=(s=>e=>s&&e instanceof s)(typeof Uint8Array<"u"&&Ze(Uint8Array)),$l=(s,e)=>{const i=(s&&s[ls]).call(s);let n;for(;(n=i.next())&&!n.done;){const a=n.value;e.call(s,a[0],a[1])}},Dl=(s,e)=>{let t;const i=[];for(;(t=s.exec(e))!==null;)i.push(t);return i},Bl=Ce("HTMLFormElement"),Fl=s=>s.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,i,n){return i.toUpperCase()+n}),{propertyIsEnumerable:Ul}=Object.prototype,ql=Ce("RegExp"),ba=(s,e)=>{const t=Object.getOwnPropertyDescriptors(s),i={};cs(t,(n,a)=>{let o;(o=e(n,a,s))!==!1&&(i[a]=o||n)}),Object.defineProperties(s,i)},Wl=s=>{ba(s,(e,t)=>{if(je(s)&&["arguments","caller","callee"].includes(t))return!1;const i=s[t];if(je(i)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},Hl=(s,e)=>{const t={},i=n=>{n.forEach(a=>{t[a]=!0})};return lt(s)?i(s):i(String(s).split(e)),t},Vl=()=>{},Kl=(s,e)=>s!=null&&Number.isFinite(s=+s)?s:e;function Gl(s){return!!(s&&je(s.append)&&s[da]==="FormData"&&s[ls])}const Ql=s=>{const e=new WeakSet,t=i=>{if(It(i)){if(e.has(i))return;if(zt(i))return i;if(!("toJSON"in i)){e.add(i);let n;if(wl(i)){n=[];for(const a of i){const o=t(a);!ct(o)&&n.push(o)}}else n=lt(i)?[]:{},cs(i,(a,o)=>{const l=t(a);!ct(l)&&(n[o]=l)});return e.delete(i),n}}return i};return t(s)},Yl=Ce("AsyncFunction"),Jl=s=>s&&(It(s)||je(s))&&je(s.then)&&je(s.catch),ga=((s,e)=>s?setImmediate:e?((t,i)=>(it.addEventListener("message",({source:n,data:a})=>{n===it&&a===t&&i.length&&i.shift()()},!1),n=>{i.push(n),it.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",je(it.postMessage)),Xl=typeof queueMicrotask<"u"?queueMicrotask.bind(it):typeof process<"u"&&process.nextTick||ga,va=s=>s!=null&&je(s[ls]),Zl=s=>s!=null&&is(s,ls)&&va(s),w={isArray:lt,isArrayBuffer:ma,isBuffer:zt,isFormData:_l,isArrayBufferView:hl,isString:ul,isNumber:pa,isBoolean:ml,isObject:It,isPlainObject:Ls,isEmptyObject:pl,isReadableStream:kl,isRequest:Ml,isResponse:Cl,isHeaders:El,isUndefined:ct,isDate:fl,isFile:xl,isReactNativeBlob:bl,isReactNative:gl,isBlob:vl,isRegExp:ql,isFunction:je,isStream:Nl,isURLSearchParams:Sl,isTypedArray:Il,isFileList:yl,forEach:cs,merge:Gi,extend:Rl,trim:Tl,stripBOM:Pl,inherits:Ll,toFlatObject:Al,kindOf:ur,kindOfTest:Ce,endsWith:Ol,toArray:zl,forEachEntry:$l,matchAll:Dl,isHTMLForm:Bl,hasOwnProperty:ss,hasOwnProp:ss,hasOwnInPrototypeChain:is,getSafeProp:cl,toSafeFlatObject:dl,reduceDescriptors:ba,freezeMethods:Wl,toObjectSet:Hl,toCamelCase:Fl,noop:Vl,toFiniteNumber:Kl,findKey:fa,global:it,isContextDefined:xa,isSpecCompliantForm:Gl,toJSONObject:Ql,isAsyncFn:Yl,isThenable:Jl,setImmediate:ga,asap:Xl,isIterable:va,isSafeIterable:Zl},ec=w.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),tc=s=>{const e={};let t,i,n;return s&&s.split(` +`).forEach(function(o){n=o.indexOf(":"),t=o.substring(0,n).trim().toLowerCase(),i=o.substring(n+1).trim();const l=w.hasOwnProp(e,t);!t||l&&w.hasOwnProp(ec,t)||(t==="set-cookie"?l?e[t].push(i):e[t]=[i]:e[t]=l?e[t]+", "+i:i)}),e};function sc(s){let e=0,t=s.length;for(;ee;){const i=s.charCodeAt(t-1);if(i!==9&&i!==32)break;t-=1}return e===0&&t===s.length?s:s.slice(e,t)}const ic=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),rc=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function mr(s,e){return w.isArray(s)?s.map(t=>mr(t,e)):sc(String(s).replace(e,""))}const nc=s=>mr(s,ic),ac=s=>mr(s,rc);function ya(s){const e=Object.create(null);return w.forEach(s.toJSON(),(t,i)=>{e[i]=ac(t)}),e}const $r=Symbol("internals");function Dt(s){return s&&String(s).trim().toLowerCase()}function As(s){return s===!1||s==null?s:w.isArray(s)?s.map(As):nc(String(s))}function oc(s){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=t.exec(s);)e[i[1]]=i[2];return e}const lc=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function yi(s){let e=0,t=s.length;for(;ee;){const i=s.charCodeAt(t-1);if(i!==9&&i!==32)break;t-=1}return e===0&&t===s.length?s:s.slice(e,t)}function cc(s){const e=s.length-1;if(e<1||s.charCodeAt(0)!==34||s.charCodeAt(e)!==34)return s;let t="";for(let i=1;i=e))return s;t+=s[i]}return t}function dc(s){const e=Object.create(null),t=String(s);let i=0,n=!1,a=!1;function o(l){const c=yi(t.slice(i,l)),d=c.indexOf("=");if(d<1)return;const h=yi(c.slice(0,d));if(!lc.test(h))return;const u=h.toLowerCase();if(u==="__proto__"||u==="constructor"||u==="prototype")return;const m=yi(c.slice(d+1));e[u]=cc(m)}for(let l=0;l/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(s.trim());function wi(s,e,t,i,n){if(w.isFunction(i))return i.call(this,e,t);if(n&&(e=t),!!w.isString(e)){if(w.isString(i))return e.indexOf(i)!==-1;if(w.isRegExp(i))return i.test(e)}}function uc(s){return s.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,i)=>t.toUpperCase()+i)}function mc(s,e){const t=w.toCamelCase(" "+e);["get","set","has"].forEach(i=>{Object.defineProperty(s,i+t,{__proto__:null,value:function(n,a,o){return this[i].call(this,e,n,a,o)},configurable:!0})})}let xe=class{constructor(e){e&&this.set(e)}set(e,t,i){const n=this;function a(l,c,d){const h=Dt(c);if(!h)return;const u=w.findKey(n,h);(!u||n[u]===void 0||d===!0||d===void 0&&n[u]!==!1)&&(n[u||c]=As(l))}const o=(l,c)=>w.forEach(l,(d,h)=>a(d,h,c));if(w.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(w.isString(e)&&(e=e.trim())&&!hc(e))o(tc(e),t);else if(w.isObject(e)&&w.isSafeIterable(e)){let l=Object.create(null),c,d;for(const h of e){if(!w.isArray(h))throw new TypeError("Object iterator must return a key-value pair");d=h[0],w.hasOwnProp(l,d)?(c=l[d],l[d]=w.isArray(c)?[...c,h[1]]:[c,h[1]]):l[d]=h[1]}o(l,t)}else e!=null&&a(t,e,i);return this}get(e,t){if(e=Dt(e),e){const i=w.findKey(this,e);if(i){const n=this[i];if(!t)return n;if(t===!0)return oc(n);if(w.isFunction(t))return t.call(this,n,i);if(w.isRegExp(t))return t.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Dt(e),e){const i=w.findKey(this,e);return!!(i&&this[i]!==void 0&&(!t||wi(this,this[i],i,t)))}return!1}delete(e,t){const i=this;let n=!1;function a(o){if(o=Dt(o),o){const l=w.findKey(i,o);l&&(!t||wi(i,i[l],l,t))&&(delete i[l],n=!0)}}return w.isArray(e)?e.forEach(a):a(e),n}clear(e){const t=Object.keys(this);let i=t.length,n=!1;for(;i--;){const a=t[i];(!e||wi(this,this[a],a,e,!0))&&(delete this[a],n=!0)}return n}normalize(e){const t=this,i={};return w.forEach(this,(n,a)=>{const o=w.findKey(i,a);if(o){t[o]=As(n),delete t[a];return}const l=e?uc(a):String(a).trim();l!==a&&delete t[a],t[l]=As(n),i[l]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return w.forEach(this,(i,n)=>{i!=null&&i!==!1&&(t[n]=e&&w.isArray(i)?i.join(", "):i)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(` +`)}getSetCookie(){const e=this.get("set-cookie");return w.isArray(e)?e:e==null||e===!1?[]:[e]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static parseParameters(e){return dc(e)}static concat(e,...t){const i=new this(e);return t.forEach(n=>i.set(n)),i}static accessor(e){const i=(this[$r]=this[$r]={accessors:{}}).accessors,n=this.prototype;function a(o){const l=Dt(o);i[l]||(mc(n,o),i[l]=!0)}return w.isArray(e)?e.forEach(a):a(e),this}};xe.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);w.reduceDescriptors(xe.prototype,({value:s},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>s,set(i){this[t]=i}}});w.freezeMethods(xe);const qs="[REDACTED ****]";function pc(s){if(w.hasOwnProp(s,"toJSON"))return!0;let e=Object.getPrototypeOf(s);for(;e&&e!==Object.prototype;){if(w.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}function fc(s,e){const t=new Set(e.map(a=>String(a).toLowerCase())),i=[],n=a=>{if(a===null||typeof a!="object"||w.isBuffer(a))return a;if(i.indexOf(a)!==-1)return;a instanceof xe&&(a=a.toJSON()),i.push(a);let o;if(w.isArray(a))o=[],a.forEach((l,c)=>{const d=n(l);w.isUndefined(d)||(o[c]=d)});else{if(!w.isPlainObject(a)&&pc(a))return i.pop(),a;o=Object.create(null);for(const[l,c]of Object.entries(a)){const d=t.has(l.toLowerCase())?qs:n(c);w.isUndefined(d)||(o[l]=d)}}return i.pop(),o};return n(s)}function Dr(s){try{return String(s)}catch{return""}}function xc(s){return s.errors.map(t=>{try{return t&&t.message?Dr(t.message):Dr(t)}catch{return""}}).filter(Boolean).join("; ")||s.name||"AggregateError"}let I=class wa extends Error{static from(e,t,i,n,a,o){let l=e.message;!l&&w.isArray(e.errors)&&e.errors.length&&(l=xc(e));const c=new wa(l,t||e.code,i,n,a);return Object.defineProperty(c,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),c.name=e.name,e.status!=null&&c.status==null&&(c.status=e.status),o&&Object.assign(c,o),c}constructor(e,t,i,n,a){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),a&&(this.response=a,this.status=a.status)}toJSON(){const e=this.config,t=e&&w.hasOwnProp(e,"redact")?e.redact:void 0,i=w.isArray(t)&&t.length>0?fc(e,t):w.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:i,code:this.code,status:this.status}}};I.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";I.ERR_BAD_OPTION="ERR_BAD_OPTION";I.ECONNABORTED="ECONNABORTED";I.ETIMEDOUT="ETIMEDOUT";I.ECONNREFUSED="ECONNREFUSED";I.ERR_NETWORK="ERR_NETWORK";I.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";I.ERR_DEPRECATED="ERR_DEPRECATED";I.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";I.ERR_BAD_REQUEST="ERR_BAD_REQUEST";I.ERR_CANCELED="ERR_CANCELED";I.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";I.ERR_INVALID_URL="ERR_INVALID_URL";I.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const bc=null,Na=100;function Qi(s){return w.isPlainObject(s)||w.isArray(s)}function ja(s){return w.endsWith(s,"[]")?s.slice(0,-2):s}function Ni(s,e,t){return s?s.concat(e).map(function(n,a){return n=ja(n),!t&&a?"["+n+"]":n}).join(t?".":""):e}function gc(s){return w.isArray(s)&&!s.some(Qi)}const vc=w.toFlatObject(w,{},null,function(e){return/^is[A-Z]/.test(e)});function si(s,e,t){if(!w.isObject(s))throw new TypeError("target must be an object");e=e||new FormData;const i=(v,S)=>{const j=w.getSafeProp(t,v);return w.isUndefined(j)?S:j},n=i("metaTokens",!0),a=i("visitor")||f,o=i("dots",!1),l=i("indexes",!1),c=i("Blob")||typeof Blob<"u"&&Blob,d=i("maxDepth",Na),h=c&&w.isSpecCompliantForm(e),u=[];if(!w.isFunction(a))throw new TypeError("visitor must be a function");function m(v){if(v===null)return"";if(w.isDate(v))return v.toISOString();if(w.isBoolean(v))return v.toString();if(!h&&w.isBlob(v))throw new I("Blob is not supported. Use a Buffer instead.");if(w.isArrayBuffer(v)||w.isTypedArray(v)){if(h&&typeof c=="function")return new c([v]);throw new I("Blob is not supported. Use a Buffer instead.",I.ERR_NOT_SUPPORT)}return v}function x(v){if(v>d)throw new I("Object is too deeply nested ("+v+" levels). Max depth: "+d,I.ERR_FORM_DATA_DEPTH_EXCEEDED)}function b(v,S){if(d===1/0)return JSON.stringify(v);const j=[];return JSON.stringify(v,function(C,E){if(!w.isObject(E))return E;for(;j.length&&j[j.length-1]!==this;)j.pop();return j.push(E),x(S+j.length-1),E})}function f(v,S,j){let k=v;if(w.isReactNative(e)&&w.isReactNativeBlob(v))return e.append(Ni(j,S,o),m(v)),!1;if(v&&!j&&typeof v=="object"){if(w.endsWith(S,"{}"))S=n?S:S.slice(0,-2),v=b(v,1);else if(w.isArray(v)&&gc(v)||(w.isFileList(v)||w.endsWith(S,"[]"))&&(k=w.toArray(v)))return S=ja(S),k.forEach(function(E,T){!(w.isUndefined(E)||E===null)&&e.append(l===!0?Ni([S],T,o):l===null?S:S+"[]",m(E))}),!1}return Qi(v)?!0:(e.append(Ni(j,S,o),m(v)),!1)}const g=Object.assign(vc,{defaultVisitor:f,convertValue:m,isVisitable:Qi});function p(v,S,j=0){if(!w.isUndefined(v)){if(x(j),u.indexOf(v)!==-1)throw new Error("Circular reference detected in "+S.join("."));u.push(v),w.forEach(v,function(C,E){(!(w.isUndefined(C)||C===null)&&a.call(e,C,w.isString(E)?E.trim():E,S,g))===!0&&p(C,S?S.concat(E):[E],j+1)}),u.pop()}}if(!w.isObject(s))throw new TypeError("data must be an object");return p(s),e}function Br(s){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(s).replace(/[!'()~]|%20/g,function(i){return e[i]})}function pr(s,e){this._pairs=[],s&&si(s,this,e)}const _a=pr.prototype;_a.append=function(e,t){this._pairs.push([e,t])};_a.toString=function(e){const t=e?i=>e.call(this,i,Br):Br;return this._pairs.map(function(n){return t(n[0])+"="+t(n[1])},"").join("&")};function yc(s){return encodeURIComponent(s).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Sa(s,e,t){if(!e)return s;s=s||"";const i=w.isFunction(t)?{serialize:t}:t,n=w.getSafeProp(i,"encode")||yc,a=w.getSafeProp(i,"serialize");let o;if(a?o=a(e,i):o=w.isURLSearchParams(e)?e.toString():new pr(e,i).toString(n),o){const l=s.indexOf("#");l!==-1&&(s=s.slice(0,l)),s+=(s.indexOf("?")===-1?"?":"&")+o}return s}const Bt=Symbol("internals");function ka(s){return s?s.length:0}function Fr(s){if(s)for(;s.length&&s[s.length-1]===null;)s.pop()}function Ft(s,e){const t=s.handlers,i=ka(t);t!==e.handlersRef?(e.handlersRef=t,e.handlerEntries.clear()):i!==e.handlersLength&&(i?e.handlerEntries.forEach(function(a,o){t[a.index]!==a.handler&&e.handlerEntries.delete(o)}):e.handlerEntries.clear()),e.handlersLength=i}class Ur{constructor(){this.handlers=[],this[Bt]={handlersRef:this.handlers,handlersLength:this.handlers.length,handlerEntries:new Map,iterationDepth:0,nextId:0}}use(e,t,i){const n={fulfilled:e,rejected:t,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null},a=this[Bt];this.handlers==null&&(this.handlers=[]),Ft(this,a);const o=a.nextId++;return this.handlers.push(n),a.handlerEntries.set(o,{handler:n,index:this.handlers.length-1}),a.handlersLength=this.handlers.length,o}eject(e){const t=this[Bt];Ft(this,t);const i=t.handlerEntries.get(e);if(i){if(t.handlerEntries.delete(e),this.handlers[i.index]!==i.handler)return;this.handlers[i.index]=null,t.iterationDepth||(Fr(this.handlers),t.handlersLength=this.handlers.length)}}clear(){this.handlers&&(this.handlers=[],Ft(this,this[Bt]))}forEach(e){const t=this[Bt];Ft(this,t),t.iterationDepth++;try{w.forEach(this.handlers,function(n){n!==null&&e(n)})}finally{--t.iterationDepth||(Ft(this,t),Fr(this.handlers),t.handlersLength=ka(this.handlers))}}}const fr={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},wc=typeof URLSearchParams<"u"?URLSearchParams:pr,Nc=typeof FormData<"u"?FormData:null,jc=typeof Blob<"u"?Blob:null,_c={isBrowser:!0,classes:{URLSearchParams:wc,FormData:Nc,Blob:jc},protocols:["http","https","file","blob","url","data"]},xr=typeof window<"u"&&typeof document<"u",Yi=typeof navigator=="object"&&navigator||void 0,Sc=xr&&(!Yi||["ReactNative","NativeScript","NS"].indexOf(Yi.product)<0),kc=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Mc=xr&&window.location.href||"http://localhost",Cc=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:xr,hasStandardBrowserEnv:Sc,hasStandardBrowserWebWorkerEnv:kc,navigator:Yi,origin:Mc},Symbol.toStringTag,{value:"Module"})),ue={...Cc,..._c};function Ec(s,e){return si(s,new ue.classes.URLSearchParams,{visitor:function(t,i,n,a){return ue.isNode&&w.isBuffer(t)?(this.append(i,t.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...e})}const qr=Na;function Ma(s){if(s>qr)throw new I("FormData field is too deeply nested ("+s+" levels). Max depth: "+qr,I.ERR_FORM_DATA_DEPTH_EXCEEDED)}function Tc(s){const e=[],t=/[^.[\]]+|\[([^.[\]]*)]/g;let i;for(;(i=t.exec(s))!==null;)Ma(e.length),e.push(i[0]==="[]"?"":i[1]||i[0]);return e}function Rc(s){const e={},t=Object.keys(s);let i;const n=t.length;let a;for(i=0;i=t.length;return o=!o&&w.isArray(n)?n.length:o,c?(w.hasOwnProp(n,o)?n[o]=w.isArray(n[o])?n[o].concat(i):[n[o],i]:n[o]=i,!l):((!w.hasOwnProp(n,o)||!w.isObject(n[o]))&&(n[o]=[]),e(t,i,n[o],a)&&w.isArray(n[o])&&(n[o]=Rc(n[o])),!l)}if(w.isFormData(s)&&w.isFunction(s.entries)){const t={};return w.forEachEntry(s,(i,n)=>{e(Tc(i),n,t,0)}),t}return null}const Ea=Object.freeze(["get","delete","head","options","post","put","patch","purge","link","unlink","query"]),gt=(s,e)=>s!=null&&w.hasOwnProp(s,e)?s[e]:void 0;function Pc(s,e,t){if(w.isString(s))try{return(e||JSON.parse)(s),w.trim(s)}catch(i){if(i.name!=="SyntaxError")throw i}return(t||JSON.stringify)(s)}const ds={transitional:fr,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const i=t.getContentType()||"",n=i.indexOf("application/json")>-1,a=w.isObject(e);if(a&&w.isHTMLForm(e)&&(e=new FormData(e)),w.isFormData(e))return n?JSON.stringify(Ca(e)):e;if(w.isArrayBuffer(e)||w.isBuffer(e)||w.isStream(e)||w.isFile(e)||w.isBlob(e)||w.isReadableStream(e))return e;if(w.isArrayBufferView(e))return e.buffer;if(w.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let l;if(a){const c=gt(this,"formSerializer");if(i.indexOf("application/x-www-form-urlencoded")>-1)return Ec(e,c).toString();if((l=w.isFileList(e))||i.indexOf("multipart/form-data")>-1){const d=gt(this,"env"),h=d&&d.FormData;return si(l?{"files[]":e}:e,h&&new h,c)}}return a||n?(t.setContentType("application/json",!1),Pc(e)):e}],transformResponse:[function(e){const t=gt(this,"transitional")||ds.transitional,i=t&&t.forcedJSONParsing,n=gt(this,"responseType"),a=n==="json";if(w.isResponse(e)||w.isReadableStream(e))return e;if(e&&w.isString(e)&&(i&&!n||a)){const l=!(t&&t.silentJSONParsing)&&a;try{return JSON.parse(e,gt(this,"parseReviver"))}catch(c){if(l)throw c.name==="SyntaxError"?I.from(c,I.ERR_BAD_RESPONSE,this,null,gt(this,"response")):c}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ue.classes.FormData,Blob:ue.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};w.forEach(Ea,s=>{ds.headers[s]={}});function ji(s,e){const t=this||ds,i=e||t,n=xe.from(i.headers);let a=i.data;return w.forEach(s,function(l){a=l.call(t,a,n.normalize(),e?e.status:void 0)}),n.normalize(),a}function Ta(s){return!!(s&&s.__CANCEL__)}let hs=class extends I{constructor(e,t,i){super(e??"canceled",I.ERR_CANCELED,t,i),this.name="CanceledError",this.__CANCEL__=!0}};function Ra(s,e,t){const i=t.config.validateStatus;!t.status||!i||i(t.status)?s(t):e(new I("Request failed with status code "+t.status,t.status>=400&&t.status<500?I.ERR_BAD_REQUEST:I.ERR_BAD_RESPONSE,t.config,t.request,t))}const Lc=/[\t\n\r]/g;function Pa(s){if(typeof s!="string")return s;let e=0;for(;e{t=u,n=null,a&&(clearTimeout(a),a=null),s(...h)};return[(...h)=>{const u=Date.now(),m=u-t;m>=i?o(h,u):(n=h,a||(a=setTimeout(()=>{a=null,o(n)},i-m)))},()=>n&&o(n),(...h)=>o(h)]}const Ws=(s,e,t=3)=>{let i=0;const n=Ac(50,250);return Oc(a=>{if(!a||!w.isNumber(a.loaded))return;const o=a.loaded,l=a.lengthComputable?a.total:void 0,c=Math.max(0,l!=null?Math.min(o,l):o),d=Math.max(0,c-i),h=n(d);i=Math.max(i,c);const u={loaded:c,total:l,progress:l?c/l:void 0,bytes:d,rate:h||void 0,estimated:h&&l?(l-c)/h:void 0,event:a,lengthComputable:l!=null,[e?"download":"upload"]:!0};s(u)},t)},Wr=(s,e)=>{const t=s!=null;return[i=>e[0]({lengthComputable:t,total:s,loaded:i}),e[1]]},Hr=(s,e=w.asap)=>(...t)=>e(()=>s(...t)),zc=ue.hasStandardBrowserEnv?((s,e)=>t=>(t=new URL(t,ue.origin),s.protocol===t.protocol&&s.host===t.host&&(e||s.port===t.port)))(new URL(ue.origin),ue.navigator&&/(msie|trident)/i.test(ue.navigator.userAgent)):()=>!0,Ic=ue.hasStandardBrowserEnv?{write(s,e,t,i,n,a,o){if(typeof document>"u")return;const l=[`${s}=${encodeURIComponent(e)}`];w.isNumber(t)&&l.push(`expires=${new Date(t).toUTCString()}`),w.isString(i)&&l.push(`path=${i}`),w.isString(n)&&l.push(`domain=${n}`),a===!0&&l.push("secure"),w.isString(o)&&l.push(`SameSite=${o}`),document.cookie=l.join("; ")},read(s){if(typeof document>"u")return null;const e=document.cookie.split(";");for(let t=0;t0&&s.charCodeAt(t-1)===47;)t--;return s.slice(0,t)+"/"+e.replace(/^\/+/,"")}const Bc=/^https?:(?!\/\/)/i;function Fc(s){return s&&s.replace(/(^|&)([^=&]*=)?[^&]+/g,(e,t,i="")=>`${t}${i}${qs}`)}function Uc(s){const e=s.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${qs}@`),t=e.indexOf("#"),n=(t===-1?e:e.slice(0,t)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${qs}`);return t===-1?n:`${n}#${Fc(e.slice(t+1))}`}function Vr(s,e){if(typeof s=="string"){const t=Pa(s);if(Bc.test(t))throw new I(`Invalid URL ${JSON.stringify(Uc(t))}: missing "//" after protocol`,I.ERR_INVALID_URL,e)}}function La(s,e,t,i){Vr(e,i);let n=!$c(e);return s&&(n||t===!1)?(Vr(s,i),Dc(s,e)):e}const Kr=s=>s instanceof xe?{...s}:s,qc=s=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(s).concat(Object.getOwnPropertySymbols(s).filter(e=>Object.getOwnPropertyDescriptor(s,e).enumerable)):Object.keys(s);function dt(s,e){s=s||{},e=e||{};const t=Object.create(null);Object.defineProperty(t,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function i(h,u,m,x){return w.isPlainObject(h)&&w.isPlainObject(u)?w.merge.call({caseless:x},h,u):w.isPlainObject(u)?w.merge({},u):w.isArray(u)?u.slice():u}function n(h,u,m,x){if(w.isUndefined(u)){if(!w.isUndefined(h))return i(void 0,h,m,x)}else return i(h,u,m,x)}function a(h,u){if(!w.isUndefined(u))return i(void 0,u)}function o(h,u){if(w.isUndefined(u)){if(!w.isUndefined(h))return i(void 0,h)}else return i(void 0,u)}function l(h){const u=w.hasOwnProp(e,"transitional")?e.transitional:void 0;if(!w.isUndefined(u))if(w.isPlainObject(u)){if(w.hasOwnProp(u,h))return u[h]}else return;const m=w.hasOwnProp(s,"transitional")?s.transitional:void 0;if(w.isPlainObject(m)&&w.hasOwnProp(m,h))return m[h]}function c(h,u,m){if(w.hasOwnProp(e,m))return i(h,u);if(w.hasOwnProp(s,m))return i(void 0,h)}const d={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutErrorMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,allowedSocketPaths:o,responseEncoding:o,validateStatus:c,headers:(h,u,m)=>n(Kr(h),Kr(u),m,!0)};return w.forEach(qc({...s,...e}),function(u){if(u==="__proto__"||u==="constructor"||u==="prototype")return;const m=w.hasOwnProp(d,u)?d[u]:n,x=w.hasOwnProp(s,u)?s[u]:void 0,b=w.hasOwnProp(e,u)?e[u]:void 0,f=m(x,b,u);w.isUndefined(f)&&m!==c||(t[u]=f)}),w.hasOwnProp(e,"validateStatus")&&w.isUndefined(e.validateStatus)&&l("validateStatusUndefinedResolves")===!1&&(w.hasOwnProp(s,"validateStatus")?t.validateStatus=i(void 0,s.validateStatus):delete t.validateStatus),t}const Wc=["content-type","content-length"];function Hc(s,e,t){if(t!=="content-only"){s.set(e);return}Object.entries(e||{}).forEach(([i,n])=>{Wc.includes(i.toLowerCase())&&s.set(i,n)})}const Vc=s=>encodeURIComponent(s).replace(/%([0-9A-F]{2})/gi,(e,t)=>String.fromCharCode(parseInt(t,16)));function Aa(s){const e=dt({},s),t=m=>w.hasOwnProp(e,m)?e[m]:void 0,i=t("data");let n=t("withXSRFToken");const a=t("xsrfHeaderName"),o=t("xsrfCookieName");let l=t("headers");const c=t("auth"),d=t("baseURL"),h=t("allowAbsoluteUrls"),u=t("url");if(e.headers=l=xe.from(l),e.url=Sa(La(d,u,h,e),t("params"),t("paramsSerializer")),c){const m=w.getSafeProp(c,"username")||"",x=w.getSafeProp(c,"password")||"";try{l.set("Authorization","Basic "+btoa(m+":"+(x?Vc(x):"")))}catch(b){throw I.from(b,I.ERR_BAD_OPTION_VALUE,s)}}if(w.isFormData(i)){const m=w.getSafeProp(i,"getHeaders");ue.hasStandardBrowserEnv||ue.hasStandardBrowserWebWorkerEnv||w.isReactNative(i)?l.setContentType(void 0):w.isFunction(m)&&Hc(l,m.call(i),t("formDataHeaderPolicy"))}if(ue.hasStandardBrowserEnv&&(w.isFunction(n)&&(n=n(e)),n===!0||n==null&&zc(e.url))){const x=a&&o&&Ic.read(o);x&&l.set(a,x)}return e}const Kc=typeof XMLHttpRequest<"u",Gc=Kc&&function(s){return new Promise(function(t,i){const n=Aa(s);let a=n.data;const o=xe.from(n.headers).normalize();let{responseType:l,onUploadProgress:c,onDownloadProgress:d}=n,h,u,m,x,b,f;function g(){x&&x(),b&&b(),n.cancelToken&&n.cancelToken.unsubscribe(h),n.signal&&n.signal.removeEventListener("abort",h)}let p=new XMLHttpRequest;p.open(n.method.toUpperCase(),n.url,!0),p.timeout=n.timeout;function v(j){if(!p)return;if(p.status===0&&(_i(Pa(n.url))||_i(ue.origin))!=="file"&&!(p.responseURL&&p.responseURL.startsWith("file:"))){i(new I("Request aborted",I.ECONNABORTED,s,p)),g(),p=null;return}try{j?f&&f(j):b&&b()}catch(T){setTimeout(()=>{throw T})}if(!p)return;const k=xe.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),E={data:!l||l==="text"||l==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:k,config:s,request:p};Ra(function(D){t(D),g()},function(D){i(D),g()},E),p=null}"onloadend"in p?p.onloadend=v:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.startsWith("file:"))||setTimeout(v)},p.onabort=function(){p&&(i(new I("Request aborted",I.ECONNABORTED,s,p)),g(),p=null)},p.onerror=function(k){const C=k&&k.message?k.message:"Network Error",E=new I(C,I.ERR_NETWORK,s,p);E.event=k||null,i(E),g(),p=null},p.ontimeout=function(){let k=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const C=n.transitional||fr;n.timeoutErrorMessage&&(k=n.timeoutErrorMessage),i(new I(k,C.clarifyTimeoutError?I.ETIMEDOUT:I.ECONNABORTED,s,p)),g(),p=null},a===void 0&&o.setContentType(null),"setRequestHeader"in p&&w.forEach(ya(o),function(k,C){p.setRequestHeader(C,k)}),w.isUndefined(n.withCredentials)||(p.withCredentials=!!n.withCredentials),l&&l!=="json"&&(p.responseType=n.responseType),d&&([m,b,f]=Ws(d,!0),p.addEventListener("progress",m)),c&&p.upload&&([u,x]=Ws(c),p.upload.addEventListener("progress",u),p.upload.addEventListener("loadend",x)),(n.cancelToken||n.signal)&&(h=j=>{p&&(i(!j||j.type?new hs(null,s,p):j),p.abort(),g(),p=null)},n.cancelToken&&n.cancelToken.subscribe(h),n.signal&&(n.signal.aborted?h():n.signal.addEventListener("abort",h)));const S=_i(n.url);if(S&&!ue.protocols.includes(S)){i(new I("Unsupported protocol "+S+":",I.ERR_BAD_REQUEST,s)),g();return}p.send(a||null)})},Qc=(s,e)=>{if(s=s?s.filter(Boolean):[],!e&&!s.length)return;const t=new AbortController;let i=!1;const n=function(c){if(!i){i=!0,o();const d=c instanceof Error?c:this.reason;t.abort(d instanceof I?d:new hs(d instanceof Error?d.message:d))}};let a=e&&setTimeout(()=>{a=null,n(new I(`timeout of ${e}ms exceeded`,I.ETIMEDOUT))},e);const o=()=>{s&&(a&&clearTimeout(a),a=null,s.forEach(c=>{c.unsubscribe?c.unsubscribe(n):c.removeEventListener("abort",n)}),s=null)};s.forEach(c=>{if(!i){if(c.aborted){n.call(c);return}c.addEventListener("abort",n,{once:!0})}});const{signal:l}=t;return l.unsubscribe=()=>w.asap(o),l},Yc=function*(s,e){let t=s.byteLength;if(t{const n=Jc(s,e);let a=0,o,l=c=>{o||(o=!0,i&&i(c))};return new ReadableStream({async pull(c){try{const{done:d,value:h}=await n.next();if(d){l(),c.close();return}let u=h.byteLength;if(t){let m=a+=u;t(m)}c.enqueue(new Uint8Array(h))}catch(d){throw l(d),d}},cancel(c){return l(c),n.return()}},{highWaterMark:2})},Qr=s=>s>=48&&s<=57||s>=65&&s<=70||s>=97&&s<=102,Oa=(s,e,t)=>e+2s<=57?s-48:(s&223)-55,Zc=s=>s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||s===43||s===47||s===45||s===95,ed=s=>s===9||s===10||s===12||s===13||s===32,td=s=>{const e=Math.floor(s/4),t=s%4;return e*3+(t===2?1:t===3?2:0)},sd=s=>{const e=s.length;let t=0;return e>0&&s.charCodeAt(e-1)===61&&(t++,e>1&&s.charCodeAt(e-2)===61&&t++),Math.floor((e-t)*3/4)},id=s=>{const e=s.length;let t=0,i=0,n=!1;for(let a=0;a0){n=!0;continue}t++}}return n||i>2||i>0&&(t+i)%4!==0||t%4===1?sd(s):td(t)},rd=(s,e)=>{if(!s||typeof s!="string"||!s.startsWith("data:"))return 0;const t=s.indexOf(",");if(t<0)return 0;const i=s.slice(5,t),n=s.slice(t+1);if(/;base64/i.test(i))return e(n);let o=0;for(let l=0,c=n.length;l=55296&&d<=56319&&l+1=56320&&h<=57343?(o+=4,l++):o+=3}else o+=3}return o};function nd(s){const e=typeof s=="string"?s.indexOf("#"):-1;return rd(e===-1?s:s.slice(0,e),id)}const br="1.20.0",Jr=64*1024,ad={cache:"default",redirect:"follow",referrer:"about:client",referrerPolicy:"",mode:"cors",integrity:"",keepalive:!1,priority:"auto",window:null},{isFunction:gs}=w,od=s=>encodeURIComponent(s).replace(/%([0-9A-F]{2})/gi,(e,t)=>String.fromCharCode(parseInt(t,16))),Xr=s=>{if(!w.isString(s))return s;try{return decodeURIComponent(s)}catch{return s}},Zr=(s,...e)=>{try{return!!s(...e)}catch{return!1}},ld=s=>{const e=s.indexOf("://");let t=s;return e!==-1&&(t=t.slice(e+3)),t.includes("@")||t.includes(":")},cd=s=>{const e=w.global!==void 0&&w.global!==null?w.global:globalThis,{ReadableStream:t,TextEncoder:i}=e;s=w.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response},s);const{fetch:n,Request:a,Response:o}=s,l=n?gs(n):typeof fetch=="function",c=gs(a),d=gs(o);if(!l)return!1;const h=l&&gs(t),u=l&&(typeof i=="function"?(p=>v=>p.encode(v))(new i):async p=>new Uint8Array(await new a(p).arrayBuffer())),m=c&&h&&Zr(()=>{let p=!1;const v=new a(ue.origin,{body:new t,method:"POST",get duplex(){return p=!0,"half"}}),S=v.headers.has("Content-Type");return v.body!=null&&v.body.cancel(),p&&!S}),x=d&&h&&Zr(()=>w.isReadableStream(new o("").body)),b={stream:x&&(p=>p.body)};l&&["text","arrayBuffer","blob","formData","stream"].forEach(p=>{!b[p]&&(b[p]=(v,S)=>{let j=v&&v[p];if(j)return j.call(v);throw new I(`Response type '${p}' is not supported`,I.ERR_NOT_SUPPORT,S)})});const f=async p=>{if(p==null)return 0;if(w.isBlob(p))return p.size;if(w.isSpecCompliantForm(p))return(await new a(ue.origin,{method:"POST",body:p}).arrayBuffer()).byteLength;if(w.isArrayBufferView(p)||w.isArrayBuffer(p))return p.byteLength;if(w.isURLSearchParams(p)&&(p=p+""),w.isString(p))return(await u(p)).byteLength},g=async(p,v)=>{const S=w.toFiniteNumber(p.getContentLength());return S??f(v)};return async p=>{let{url:v,method:S,data:j,signal:k,cancelToken:C,timeout:E,onDownloadProgress:T,onUploadProgress:D,responseType:O,headers:M,withCredentials:R="same-origin",fetchOptions:L,maxContentLength:$,maxBodyLength:z,maxRedirects:V}=Aa(p);const q=w.isNumber($)&&$>-1,Z=w.isNumber(z)&&z>-1,ae=K=>w.hasOwnProp(p,K)?p[K]:void 0;let A=n||fetch;O=O?(O+"").toLowerCase():"text";let H=Qc([k,C&&C.toAbortSignal()],E),_=null;const B=H&&H.unsubscribe&&(()=>{H.unsubscribe()});let Y,F=null;const le=()=>new I("Request body larger than maxBodyLength limit",I.ERR_BAD_REQUEST,p,_);try{let K;const te=ae("auth");if(te){const W=w.getSafeProp(te,"username")||"",X=w.getSafeProp(te,"password")||"";K={username:W,password:X}}if(ld(v)){const W=new URL(v,ue.origin);if(!K&&(W.username||W.password)){const X=Xr(W.username),ke=Xr(W.password);K={username:X,password:ke}}(W.username||W.password)&&(W.username="",W.password="",v=W.href)}if(K&&(M.delete("authorization"),M.set("Authorization","Basic "+btoa(od((K.username||"")+":"+(K.password||""))))),q&&typeof v=="string"&&v.startsWith("data:")&&nd(v)>$)throw new I("maxContentLength size of "+$+" exceeded",I.ERR_BAD_RESPONSE,p,_);if(Z&&S!=="get"&&S!=="head"){const W=await f(j);if(typeof W=="number"&&isFinite(W)&&(Y=W,W>z))throw le()}const be=Z&&(w.isReadableStream(j)||w.isStream(j)),Se=(W,X,ke)=>Gr(W,Jr,ze=>{if(Z&&ze>z)throw F=le();X&&X(ze)},ke);if(m&&S!=="get"&&S!=="head"&&(D||be)){if(Y=Y??await g(M,j),Y!==0||be){let W=new a(v,{method:"POST",body:j,duplex:"half"}),X;if(w.isFormData(j)&&(X=W.headers.get("content-type"))&&M.setContentType(X),W.body){const[ke,ze]=D&&Wr(Y,Ws(Hr(D)))||[];j=Se(W.body,ke,ze)}}}else if(be&&!c&&h&&S!=="get"&&S!=="head")j=Se(j);else if(be&&c&&!m&&S!=="get"&&S!=="head")throw new I("Stream request bodies are not supported by the current fetch implementation",I.ERR_NOT_SUPPORT,p,_);w.isString(R)||(R=R?"include":"omit");const tt=c&&"credentials"in a.prototype;if(w.isFormData(j)){const W=M.getContentType();W&&/^multipart\/form-data/i.test(W)&&!/boundary=/i.test(W)&&M.delete("content-type")}M.set("User-Agent","axios/"+br,!1);const ge=L==null?L:Object.assign(Object.create(null),L);ge&&(delete ge.body,delete ge.headers,delete ge.method,delete ge.signal,delete ge.duplex,delete ge.credentials);const we=Object.assign(Object.create(null),ge,{signal:H,method:S.toUpperCase(),headers:ya(M.normalize()),body:j,duplex:"half",credentials:tt?R:void 0});c&&(w.forEach(ad,(W,X)=>{we[X]===void 0&&(we[X]=W)}),we.signal===void 0&&(we.signal=null),we.body===void 0&&(we.body=null)),V===0&&(we.redirect="manual",ge&&(ge.redirect="manual")),_=c&&new a(v,we);let N=await(c?A(_,ge):A(v,we));const Q=xe.from(N.headers);if(q){const W=w.toFiniteNumber(Q.getContentLength());if(W!=null&&W>$)throw new I("maxContentLength size of "+$+" exceeded",I.ERR_BAD_RESPONSE,p,_)}const J=x&&(O==="stream"||O==="response");if(x&&N.body&&(T||q||J&&B)){const W={};["status","statusText","headers"].forEach(qe=>{W[qe]=N[qe]});const X=w.toFiniteNumber(Q.getContentLength()),[ke,ze]=T&&Wr(X,Ws(Hr(T),!0))||[];let xs=0;const Ee=qe=>{if(q&&(xs=qe,xs>$))throw new I("maxContentLength size of "+$+" exceeded",I.ERR_BAD_RESPONSE,p,_);ke&&ke(qe)};N=new o(Gr(N.body,Jr,Ee,()=>{ze&&ze(),B&&B()}),W)}O=O||"text";let ee=await b[w.findKey(b,O)||"text"](N,p);if(q&&!x&&!J){let W;if(ee!=null&&(typeof ee.byteLength=="number"?W=ee.byteLength:typeof ee.size=="number"?W=ee.size:typeof ee=="string"&&(W=typeof i=="function"?new i().encode(ee).byteLength:ee.length)),typeof W=="number"&&W>$)throw new I("maxContentLength size of "+$+" exceeded",I.ERR_BAD_RESPONSE,p,_)}return!J&&B&&B(),await new Promise((W,X)=>{Ra(W,X,{data:ee,headers:xe.from(N.headers),status:N.status,statusText:N.statusText,config:p,request:_})})}catch(K){if(B&&B(),H&&H.aborted&&H.reason instanceof I){const te=H.reason;throw te.config=p,_&&(te.request=_),K!==te&&Object.defineProperty(te,"cause",{__proto__:null,value:K,writable:!0,enumerable:!1,configurable:!0}),te}if(F)throw _&&!F.request&&(F.request=_),F;if(K instanceof I)throw _&&!K.request&&(K.request=_),K;if(K&&K.name==="TypeError"&&/Load failed|fetch/i.test(K.message)){const te=new I("Network Error",I.ERR_NETWORK,p,_,K&&K.response);throw Object.defineProperty(te,"cause",{__proto__:null,value:K.cause||K,writable:!0,enumerable:!1,configurable:!0}),te}throw I.from(K,K&&K.code,p,_,K&&K.response)}}},dd=new Map,za=s=>{let e=s&&s.env||{};const{fetch:t,Request:i,Response:n}=e,a=[i,n,t];let o=a.length,l=o,c,d,h=dd;for(;l--;)c=a[l],d=h.get(c),d===void 0&&h.set(c,d=l?new Map:cd(e)),h=d;return d};za();const gr={http:bc,xhr:Gc,fetch:{get:za}};w.forEach(gr,(s,e)=>{if(s){try{Object.defineProperty(s,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(s,"adapterName",{__proto__:null,value:e})}});const en=s=>`- ${s}`,hd=s=>w.isFunction(s)||s===null||s===!1;function ud(s,e){s=w.isArray(s)?s:[s];const{length:t}=s;let i,n;const a={};for(let o=0;o`adapter ${c} `+(d===!1?"is not supported by the environment":"is not available in the build"));let l=t?o.length>1?`since : +`+o.map(en).join(` +`):" "+en(o[0]):"as no adapter specified";throw new I("There is no suitable adapter to dispatch the request "+l,I.ERR_NOT_SUPPORT)}return n}const Ia={getAdapter:ud,adapters:gr};function Si(s){if(s.cancelToken&&s.cancelToken.throwIfRequested(),s.signal&&s.signal.aborted)throw new hs(null,s)}function ki(s){const e=w.toSafeFlatObject(s);return Si(e),e.headers=xe.from(w.getSafeProp(e,"headers")),e.data=ji.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Ia.getAdapter(e.adapter||ds.adapter,e)(e).then(function(n){Si(e),e.response=n;try{n.data=ji.call(e,e.transformResponse,n)}finally{delete e.response}return n.headers=xe.from(n.headers),n},function(n){if(!Ta(n)&&(Si(e),n&&n.response)){e.response=n.response;try{n.response.data=ji.call(e,e.transformResponse,n.response)}finally{delete e.response}n.response.headers=xe.from(n.response.headers)}return Promise.reject(n)})}const ii={};["object","boolean","number","function","string","symbol"].forEach((s,e)=>{ii[s]=function(i){return typeof i===s||"a"+(e<1?"n ":" ")+s}});const tn={};ii.transitional=function(e,t,i){function n(a,o){return"[Axios v"+br+"] Transitional option '"+a+"'"+o+(i?". "+i:"")}return(a,o,l)=>{if(e===!1)throw new I(n(o," has been removed"+(t?" in "+t:"")),I.ERR_DEPRECATED);return t&&!tn[o]&&(tn[o]=!0,console.warn(n(o," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(a,o,l):!0}};ii.spelling=function(e){return(t,i)=>(console.warn(`${i} is likely a misspelling of ${e}`),!0)};function md(s,e,t){if(typeof s!="object"||s===null)throw new I("options must be an object",I.ERR_BAD_OPTION_VALUE);const i=Object.keys(s);let n=i.length;for(;n-- >0;){const a=i[n],o=Object.prototype.hasOwnProperty.call(e,a)?e[a]:void 0;if(o){const l=s[a],c=l===void 0||o(l,a,s);if(c!==!0)throw new I("option "+a+" must be "+c,I.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new I("Unknown option "+a,I.ERR_BAD_OPTION)}}const Os={assertOptions:md,validators:ii},fe=Os.validators;let rt=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Ur,response:new Ur}}async request(e,t){try{return await this._request(e,t)}catch(i){if(i instanceof Error)try{let n={};Error.captureStackTrace?Error.captureStackTrace(n):n=new Error;const a=n.stack;let o="";if(typeof a=="string"){const l=a.indexOf(` +`);o=l===-1?"":a.slice(l+1)}if(!i.stack)i.stack=o;else if(o){const l=o.indexOf(` +`),c=l===-1?-1:o.indexOf(` +`,l+1),d=c===-1?"":o.slice(c+1);String(i.stack).endsWith(d)||(i.stack+=` +`+o)}}catch{}throw i}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=dt(this.defaults,t);const{transitional:i,paramsSerializer:n,headers:a}=t;i!==void 0&&Os.assertOptions(i,{silentJSONParsing:fe.transitional(fe.boolean),forcedJSONParsing:fe.transitional(fe.boolean),clarifyTimeoutError:fe.transitional(fe.boolean),legacyInterceptorReqResOrdering:fe.transitional(fe.boolean),advertiseZstdAcceptEncoding:fe.transitional(fe.boolean),validateStatusUndefinedResolves:fe.transitional(fe.boolean)},!1),n!=null&&(w.isFunction(n)?t.paramsSerializer={serialize:n}:Os.assertOptions(n,{encode:fe.function,serialize:fe.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Os.assertOptions(t,{baseUrl:fe.spelling("baseURL"),withXsrfToken:fe.spelling("withXSRFToken")},!0),t.method=(w.getSafeProp(t,"method")||w.getSafeProp(this.defaults,"method")||"get").toLowerCase();let o=a&&w.merge(a.common,a[t.method]);a&&w.forEach(Ea.concat("common"),b=>{delete a[b]}),t.headers=xe.concat(o,a);const l=[];let c=!0;this.interceptors.request.forEach(function(f){if(typeof f.runWhen=="function"&&f.runWhen(t)===!1)return;c=c&&f.synchronous;const g=t.transitional||fr;g&&g.legacyInterceptorReqResOrdering?l.unshift(f.fulfilled,f.rejected):l.push(f.fulfilled,f.rejected)});const d=[];this.interceptors.response.forEach(function(f){d.push(f.fulfilled,f.rejected)});let h,u=0,m;if(!c){const b=[ki.bind(this),void 0];for(b.unshift(...l),b.push(...d),m=b.length,h=Promise.resolve(t);uki.call(this,x)))}catch(p){h=Promise.reject(p)}break}}if(!h)try{h=ki.call(this,x)}catch(b){h=Promise.reject(b)}for(u=0,m=d.length;u{if(!i._listeners)return;let a=i._listeners.length;for(;a-- >0;)i._listeners[a](n);i._listeners=null}),this.promise.then=n=>{let a;const o=new Promise(l=>{i.subscribe(l),a=l}).then(n);return o.cancel=function(){i.unsubscribe(a)},o},e(function(a,o,l){i.reason||(i.reason=new hs(a,o,l),t(i.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=i=>{e.abort(i)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new $a(function(n){e=n}),cancel:e}}};function fd(s){return function(t){return s.apply(null,t)}}function xd(s){return w.isObject(s)&&s.isAxiosError===!0}const zs={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(zs).forEach(([s,e])=>{zs[e]===void 0&&(zs[e]=s)});function Da(s){const e=new rt(s),t=ca(rt.prototype.request,e);return w.extend(t,rt.prototype,e,{allOwnKeys:!0}),w.extend(t,e,null,{allOwnKeys:!0}),t.create=function(n){return Da(dt(s,n))},t}const de=Da(ds);de.Axios=rt;de.CanceledError=hs;de.CancelToken=pd;de.isCancel=Ta;de.VERSION=br;de.toFormData=si;de.AxiosError=I;de.Cancel=de.CanceledError;de.all=function(e){return Promise.all(e)};de.spread=fd;de.isAxiosError=xd;de.mergeConfig=dt;de.AxiosHeaders=xe;de.formToJSON=s=>Ca(w.isHTMLForm(s)?new FormData(s):s);de.getAdapter=Ia.getAdapter;de.HttpStatusCode=zs;de.default=de;const{Axios:bf,AxiosError:gf,CanceledError:vf,isCancel:yf,CancelToken:wf,VERSION:Nf,all:jf,Cancel:_f,isAxiosError:Sf,spread:kf,toFormData:Mf,AxiosHeaders:Cf,HttpStatusCode:Ef,formToJSON:Tf,getAdapter:Rf,mergeConfig:Pf,create:Lf}=de,bd="https://agus1111-perps-terminal.hf.space",Ji="perps_api_token";function gd(){if(typeof window<"u"){const s=localStorage.getItem(Ji);if(s)return s.trim()}return""}function Af(s){const e=s.trim();typeof window<"u"&&(e?localStorage.setItem(Ji,e):localStorage.removeItem(Ji),window.dispatchEvent(new Event("perps_api_token_changed")))}function vd(){return typeof window>"u"?!1:!!(window.Capacitor?.isNativePlatform?.()||window.Capacitor||window.location.hostname==="localhost"&&window.location.port==="")}function ri(){if(typeof window<"u"){const s=localStorage.getItem("perps_server_url");if(s)return s.trim().replace(/\/+$/,"")}return vd()?bd:typeof window<"u"&&window.location.port==="5173"?"http://127.0.0.1:8000":""}function Of(s){const e=s.trim().replace(/\/+$/,"");e?localStorage.setItem("perps_server_url",e):localStorage.removeItem("perps_server_url"),typeof window<"u"&&window.dispatchEvent(new Event("perps_server_url_changed"))}const yd=ri(),ie=de.create({baseURL:yd,timeout:0,headers:{"Content-Type":"application/json"}});ie.interceptors.request.use(s=>{s.baseURL=ri();const e=gd();return e&&s.headers.set("Authorization",`Bearer ${e}`),s});ie.interceptors.response.use(s=>s,s=>{const e=s.response?.status,t=s.response?.data?.detail||s.response?.data?.message||s.message||"An unexpected error occurred",i=Object.assign(new Error(t),{status:e});return Promise.reject(i)});function Qe(){const s=ri();if(s){const e=s.startsWith("https://")?"wss://":"ws://",t=s.replace(/^https?:\/\//,"");return`${e}${t}/ws/signals`}return typeof window<"u"?window.location.port==="5173"?"ws://127.0.0.1:8000/ws/signals":`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/signals`:null}function wd(s){const e=s.toUpperCase().replace(/[/-]/g,""),t=ri();if(t){const i=t.startsWith("https://")?"wss://":"ws://",n=t.replace(/^https?:\/\//,"");return`${i}${n}/ws/chart/${e}`}return typeof window<"u"?window.location.port==="5173"?`ws://127.0.0.1:8000/ws/chart/${e}`:`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/chart/${e}`:null}Qe();const ni={getAll:async()=>{const{data:s}=await ie.get("/api/pairs");return s},validate:async s=>{const{data:e}=await ie.post("/api/pairs/validate",{symbol:s});return e},add:async s=>{const{data:e}=await ie.post("/api/pairs",{symbol:s});return e},remove:async s=>{await ie.delete(`/api/pairs/${s}`)},toggleActive:async(s,e)=>{const{data:t}=await ie.patch(`/api/pairs/${s}/toggle`,{is_active:e});return t}},ai=["pairs"];function us(){return Zt({queryKey:ai,queryFn:ni.getAll,placeholderData:s=>s,refetchInterval:6e4,refetchOnWindowFocus:!1,retry:3,staleTime:6e4})}function zf(){const s=os();return as({mutationFn:e=>ni.add(e),onSuccess:()=>{s.invalidateQueries({queryKey:ai}),s.invalidateQueries({queryKey:["signals"]})}})}function Nd(){const s=os();return as({mutationFn:e=>ni.remove(e),onSuccess:()=>{s.invalidateQueries({queryKey:ai}),s.invalidateQueries({queryKey:["signals"]})}})}function If(){return as({mutationFn:s=>ni.validate(s)})}function Ba(s){var e,t,i="";if(typeof s=="string"||typeof s=="number")i+=s;else if(typeof s=="object")if(Array.isArray(s)){var n=s.length;for(e=0;e{const e=Sd(s),{conflictingClassGroups:t,conflictingClassGroupModifiers:i}=s;return{getClassGroupId:o=>{const l=o.split(vr);return l[0]===""&&l.length!==1&&l.shift(),Fa(l,e)||_d(o)},getConflictingClassGroupIds:(o,l)=>{const c=t[o]||[];return l&&i[o]?[...c,...i[o]]:c}}},Fa=(s,e)=>{if(s.length===0)return e.classGroupId;const t=s[0],i=e.nextPart.get(t),n=i?Fa(s.slice(1),i):void 0;if(n)return n;if(e.validators.length===0)return;const a=s.join(vr);return e.validators.find(({validator:o})=>o(a))?.classGroupId},sn=/^\[(.+)\]$/,_d=s=>{if(sn.test(s)){const e=sn.exec(s)[1],t=e?.substring(0,e.indexOf(":"));if(t)return"arbitrary.."+t}},Sd=s=>{const{theme:e,prefix:t}=s,i={nextPart:new Map,validators:[]};return Md(Object.entries(s.classGroups),t).forEach(([a,o])=>{Xi(o,i,a,e)}),i},Xi=(s,e,t,i)=>{s.forEach(n=>{if(typeof n=="string"){const a=n===""?e:rn(e,n);a.classGroupId=t;return}if(typeof n=="function"){if(kd(n)){Xi(n(i),e,t,i);return}e.validators.push({validator:n,classGroupId:t});return}Object.entries(n).forEach(([a,o])=>{Xi(o,rn(e,a),t,i)})})},rn=(s,e)=>{let t=s;return e.split(vr).forEach(i=>{t.nextPart.has(i)||t.nextPart.set(i,{nextPart:new Map,validators:[]}),t=t.nextPart.get(i)}),t},kd=s=>s.isThemeGetter,Md=(s,e)=>e?s.map(([t,i])=>{const n=i.map(a=>typeof a=="string"?e+a:typeof a=="object"?Object.fromEntries(Object.entries(a).map(([o,l])=>[e+o,l])):a);return[t,n]}):s,Cd=s=>{if(s<1)return{get:()=>{},set:()=>{}};let e=0,t=new Map,i=new Map;const n=(a,o)=>{t.set(a,o),e++,e>s&&(e=0,i=t,t=new Map)};return{get(a){let o=t.get(a);if(o!==void 0)return o;if((o=i.get(a))!==void 0)return n(a,o),o},set(a,o){t.has(a)?t.set(a,o):n(a,o)}}},Ua="!",Ed=s=>{const{separator:e,experimentalParseClassName:t}=s,i=e.length===1,n=e[0],a=e.length,o=l=>{const c=[];let d=0,h=0,u;for(let g=0;gh?u-h:void 0;return{modifiers:c,hasImportantModifier:x,baseClassName:b,maybePostfixModifierPosition:f}};return t?l=>t({className:l,parseClassName:o}):o},Td=s=>{if(s.length<=1)return s;const e=[];let t=[];return s.forEach(i=>{i[0]==="["?(e.push(...t.sort(),i),t=[]):t.push(i)}),e.push(...t.sort()),e},Rd=s=>({cache:Cd(s.cacheSize),parseClassName:Ed(s),...jd(s)}),Pd=/\s+/,Ld=(s,e)=>{const{parseClassName:t,getClassGroupId:i,getConflictingClassGroupIds:n}=e,a=[],o=s.trim().split(Pd);let l="";for(let c=o.length-1;c>=0;c-=1){const d=o[c],{modifiers:h,hasImportantModifier:u,baseClassName:m,maybePostfixModifierPosition:x}=t(d);let b=!!x,f=i(b?m.substring(0,x):m);if(!f){if(!b){l=d+(l.length>0?" "+l:l);continue}if(f=i(m),!f){l=d+(l.length>0?" "+l:l);continue}b=!1}const g=Td(h).join(":"),p=u?g+Ua:g,v=p+f;if(a.includes(v))continue;a.push(v);const S=n(f,b);for(let j=0;j0?" "+l:l)}return l};function Ad(){let s=0,e,t,i="";for(;s{if(typeof s=="string")return s;let e,t="";for(let i=0;iu(h),s());return t=Rd(d),i=t.cache.get,n=t.cache.set,a=l,l(c)}function l(c){const d=i(c);if(d)return d;const h=Ld(c,t);return n(c,h),h}return function(){return a(Ad.apply(null,arguments))}}const ne=s=>{const e=t=>t[s]||[];return e.isThemeGetter=!0,e},Wa=/^\[(?:([a-z-]+):)?(.+)\]$/i,zd=/^\d+\/\d+$/,Id=new Set(["px","full","screen"]),$d=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Dd=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Bd=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Fd=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Ud=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ie=s=>St(s)||Id.has(s)||zd.test(s),We=s=>$t(s,"length",Yd),St=s=>!!s&&!Number.isNaN(Number(s)),Mi=s=>$t(s,"number",St),Ut=s=>!!s&&Number.isInteger(Number(s)),qd=s=>s.endsWith("%")&&St(s.slice(0,-1)),G=s=>Wa.test(s),He=s=>$d.test(s),Wd=new Set(["length","size","percentage"]),Hd=s=>$t(s,Wd,Ha),Vd=s=>$t(s,"position",Ha),Kd=new Set(["image","url"]),Gd=s=>$t(s,Kd,Xd),Qd=s=>$t(s,"",Jd),qt=()=>!0,$t=(s,e,t)=>{const i=Wa.exec(s);return i?i[1]?typeof e=="string"?i[1]===e:e.has(i[1]):t(i[2]):!1},Yd=s=>Dd.test(s)&&!Bd.test(s),Ha=()=>!1,Jd=s=>Fd.test(s),Xd=s=>Ud.test(s),Zd=()=>{const s=ne("colors"),e=ne("spacing"),t=ne("blur"),i=ne("brightness"),n=ne("borderColor"),a=ne("borderRadius"),o=ne("borderSpacing"),l=ne("borderWidth"),c=ne("contrast"),d=ne("grayscale"),h=ne("hueRotate"),u=ne("invert"),m=ne("gap"),x=ne("gradientColorStops"),b=ne("gradientColorStopPositions"),f=ne("inset"),g=ne("margin"),p=ne("opacity"),v=ne("padding"),S=ne("saturate"),j=ne("scale"),k=ne("sepia"),C=ne("skew"),E=ne("space"),T=ne("translate"),D=()=>["auto","contain","none"],O=()=>["auto","hidden","clip","visible","scroll"],M=()=>["auto",G,e],R=()=>[G,e],L=()=>["",Ie,We],$=()=>["auto",St,G],z=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],V=()=>["solid","dashed","dotted","double","none"],q=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Z=()=>["start","end","center","between","around","evenly","stretch"],ae=()=>["","0",G],A=()=>["auto","avoid","all","avoid-page","page","left","right","column"],H=()=>[St,G];return{cacheSize:500,separator:":",theme:{colors:[qt],spacing:[Ie,We],blur:["none","",He,G],brightness:H(),borderColor:[s],borderRadius:["none","","full",He,G],borderSpacing:R(),borderWidth:L(),contrast:H(),grayscale:ae(),hueRotate:H(),invert:ae(),gap:R(),gradientColorStops:[s],gradientColorStopPositions:[qd,We],inset:M(),margin:M(),opacity:H(),padding:R(),saturate:H(),scale:H(),sepia:ae(),skew:H(),space:R(),translate:R()},classGroups:{aspect:[{aspect:["auto","square","video",G]}],container:["container"],columns:[{columns:[He]}],"break-after":[{"break-after":A()}],"break-before":[{"break-before":A()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...z(),G]}],overflow:[{overflow:O()}],"overflow-x":[{"overflow-x":O()}],"overflow-y":[{"overflow-y":O()}],overscroll:[{overscroll:D()}],"overscroll-x":[{"overscroll-x":D()}],"overscroll-y":[{"overscroll-y":D()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[f]}],"inset-x":[{"inset-x":[f]}],"inset-y":[{"inset-y":[f]}],start:[{start:[f]}],end:[{end:[f]}],top:[{top:[f]}],right:[{right:[f]}],bottom:[{bottom:[f]}],left:[{left:[f]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Ut,G]}],basis:[{basis:M()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",G]}],grow:[{grow:ae()}],shrink:[{shrink:ae()}],order:[{order:["first","last","none",Ut,G]}],"grid-cols":[{"grid-cols":[qt]}],"col-start-end":[{col:["auto",{span:["full",Ut,G]},G]}],"col-start":[{"col-start":$()}],"col-end":[{"col-end":$()}],"grid-rows":[{"grid-rows":[qt]}],"row-start-end":[{row:["auto",{span:[Ut,G]},G]}],"row-start":[{"row-start":$()}],"row-end":[{"row-end":$()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",G]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",G]}],gap:[{gap:[m]}],"gap-x":[{"gap-x":[m]}],"gap-y":[{"gap-y":[m]}],"justify-content":[{justify:["normal",...Z()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...Z(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...Z(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[v]}],px:[{px:[v]}],py:[{py:[v]}],ps:[{ps:[v]}],pe:[{pe:[v]}],pt:[{pt:[v]}],pr:[{pr:[v]}],pb:[{pb:[v]}],pl:[{pl:[v]}],m:[{m:[g]}],mx:[{mx:[g]}],my:[{my:[g]}],ms:[{ms:[g]}],me:[{me:[g]}],mt:[{mt:[g]}],mr:[{mr:[g]}],mb:[{mb:[g]}],ml:[{ml:[g]}],"space-x":[{"space-x":[E]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[E]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",G,e]}],"min-w":[{"min-w":[G,e,"min","max","fit"]}],"max-w":[{"max-w":[G,e,"none","full","min","max","fit","prose",{screen:[He]},He]}],h:[{h:[G,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[G,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[G,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[G,e,"auto","min","max","fit"]}],"font-size":[{text:["base",He,We]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Mi]}],"font-family":[{font:[qt]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",G]}],"line-clamp":[{"line-clamp":["none",St,Mi]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Ie,G]}],"list-image":[{"list-image":["none",G]}],"list-style-type":[{list:["none","disc","decimal",G]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[p]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[p]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...V(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Ie,We]}],"underline-offset":[{"underline-offset":["auto",Ie,G]}],"text-decoration-color":[{decoration:[s]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:R()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",G]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",G]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[p]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...z(),Vd]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Hd]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Gd]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[b]}],"gradient-via-pos":[{via:[b]}],"gradient-to-pos":[{to:[b]}],"gradient-from":[{from:[x]}],"gradient-via":[{via:[x]}],"gradient-to":[{to:[x]}],rounded:[{rounded:[a]}],"rounded-s":[{"rounded-s":[a]}],"rounded-e":[{"rounded-e":[a]}],"rounded-t":[{"rounded-t":[a]}],"rounded-r":[{"rounded-r":[a]}],"rounded-b":[{"rounded-b":[a]}],"rounded-l":[{"rounded-l":[a]}],"rounded-ss":[{"rounded-ss":[a]}],"rounded-se":[{"rounded-se":[a]}],"rounded-ee":[{"rounded-ee":[a]}],"rounded-es":[{"rounded-es":[a]}],"rounded-tl":[{"rounded-tl":[a]}],"rounded-tr":[{"rounded-tr":[a]}],"rounded-br":[{"rounded-br":[a]}],"rounded-bl":[{"rounded-bl":[a]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[p]}],"border-style":[{border:[...V(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[p]}],"divide-style":[{divide:V()}],"border-color":[{border:[n]}],"border-color-x":[{"border-x":[n]}],"border-color-y":[{"border-y":[n]}],"border-color-s":[{"border-s":[n]}],"border-color-e":[{"border-e":[n]}],"border-color-t":[{"border-t":[n]}],"border-color-r":[{"border-r":[n]}],"border-color-b":[{"border-b":[n]}],"border-color-l":[{"border-l":[n]}],"divide-color":[{divide:[n]}],"outline-style":[{outline:["",...V()]}],"outline-offset":[{"outline-offset":[Ie,G]}],"outline-w":[{outline:[Ie,We]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:L()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[p]}],"ring-offset-w":[{"ring-offset":[Ie,We]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",He,Qd]}],"shadow-color":[{shadow:[qt]}],opacity:[{opacity:[p]}],"mix-blend":[{"mix-blend":[...q(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":q()}],filter:[{filter:["","none"]}],blur:[{blur:[t]}],brightness:[{brightness:[i]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",He,G]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[u]}],saturate:[{saturate:[S]}],sepia:[{sepia:[k]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[t]}],"backdrop-brightness":[{"backdrop-brightness":[i]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[u]}],"backdrop-opacity":[{"backdrop-opacity":[p]}],"backdrop-saturate":[{"backdrop-saturate":[S]}],"backdrop-sepia":[{"backdrop-sepia":[k]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[o]}],"border-spacing-x":[{"border-spacing-x":[o]}],"border-spacing-y":[{"border-spacing-y":[o]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",G]}],duration:[{duration:H()}],ease:[{ease:["linear","in","out","in-out",G]}],delay:[{delay:H()}],animate:[{animate:["none","spin","ping","pulse","bounce",G]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[j]}],"scale-x":[{"scale-x":[j]}],"scale-y":[{"scale-y":[j]}],rotate:[{rotate:[Ut,G]}],"translate-x":[{"translate-x":[T]}],"translate-y":[{"translate-y":[T]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",G]}],accent:[{accent:["auto",s]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",G]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":R()}],"scroll-mx":[{"scroll-mx":R()}],"scroll-my":[{"scroll-my":R()}],"scroll-ms":[{"scroll-ms":R()}],"scroll-me":[{"scroll-me":R()}],"scroll-mt":[{"scroll-mt":R()}],"scroll-mr":[{"scroll-mr":R()}],"scroll-mb":[{"scroll-mb":R()}],"scroll-ml":[{"scroll-ml":R()}],"scroll-p":[{"scroll-p":R()}],"scroll-px":[{"scroll-px":R()}],"scroll-py":[{"scroll-py":R()}],"scroll-ps":[{"scroll-ps":R()}],"scroll-pe":[{"scroll-pe":R()}],"scroll-pt":[{"scroll-pt":R()}],"scroll-pr":[{"scroll-pr":R()}],"scroll-pb":[{"scroll-pb":R()}],"scroll-pl":[{"scroll-pl":R()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",G]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[Ie,We,Mi]}],stroke:[{stroke:[s,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},ps=Od(Zd);function eh(...s){return ps(ms(s))}const Va=y.createContext(null);function bt(){const s=y.useContext(Va);if(!s)throw new Error("useToast must be used within ToastProvider");return s}function th({children:s}){const[e,t]=y.useState([]),i=y.useCallback((a,o="info")=>{const l=Math.random().toString(36).slice(2);t(c=>[...c,{id:l,message:a,variant:o}]),setTimeout(()=>{t(c=>c.filter(d=>d.id!==l))},4e3)},[]),n=y.useCallback(a=>{t(o=>o.filter(l=>l.id!==a))},[]);return r.jsxs(Va.Provider,{value:{toast:i},children:[s,r.jsx("div",{className:"fixed bottom-4 right-4 z-[100] flex flex-col gap-2 pointer-events-none",children:e.map(a=>r.jsx(ih,{item:a,onRemove:n},a.id))})]})}const sh={success:{icon:r.jsx(ra,{size:16}),cls:"border-signal-long/30 text-signal-long"},error:{icon:r.jsx(or,{size:16}),cls:"border-signal-short/30 text-signal-short"},info:{icon:r.jsx(Io,{size:16}),cls:"border-accent-blue/30 text-accent-blue"}};function ih({item:s,onRemove:e}){const[t,i]=y.useState(!1),n=sh[s.variant];return y.useEffect(()=>{requestAnimationFrame(()=>i(!0))},[]),r.jsxs("div",{className:eh("pointer-events-auto flex items-center gap-3 bg-bg-card border rounded-lg px-4 py-3 shadow-xl","transition-all duration-300",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",n.cls),style:{minWidth:"280px",maxWidth:"400px"},children:[n.icon,r.jsx("p",{className:"text-sm text-text-primary flex-1",children:s.message}),r.jsx("button",{onClick:()=>e(s.id),className:"text-text-secondary hover:text-text-primary transition-colors",children:r.jsx(Et,{size:14})})]})}function Hs({pair:s,signal:e,isSelected:t,onSelect:i}){const{mutate:n,isPending:a}=Nd(),{toast:o}=bt(),l=u=>{u.stopPropagation(),n(s.id,{onSuccess:()=>o(`${s.symbol} removed`,"info"),onError:m=>o(m.message,"error")})},c=e?.streak??s.streak_count??0,d=s.symbol.replace(/(USDT|USDC|USD|BUSD|EUR|PERP)$/,""),h=s.symbol.slice(d.length)||"USDT";return r.jsxs("div",{className:`group relative flex flex-col gap-1.5 px-3 py-2.5 rounded-lg cursor-pointer transition-colors + ${t?"bg-accent-blue/10 border border-accent-blue/30":"hover:bg-bg-elevated border border-transparent"} + ${s.is_active?"":"opacity-50"} + `,onClick:()=>i(s.symbol),children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${s.is_active?"bg-signal-long":"bg-text-muted"}`}),r.jsxs("div",{className:"flex items-baseline gap-0.5 flex-1 min-w-0",children:[r.jsx("span",{className:"font-mono text-sm font-bold text-text-primary whitespace-nowrap",children:d}),r.jsxs("span",{className:"font-mono text-[10px] text-text-muted/70",children:["/",h]})]}),c>=2&&r.jsxs("span",{className:"text-[10px] font-mono font-bold px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-400 border border-amber-500/30 shrink-0 flex items-center gap-0.5 animate-pulse",title:`Consistent Streak: ${c}x cycles`,children:["🔥 ",c,"x"]}),e&&r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx(hr,{direction:e.direction,size:"sm"}),r.jsx("span",{className:`text-[10px] font-mono font-bold px-1.5 py-0.5 rounded border ${e.conviction>=6?"bg-signal-long/15 text-signal-long border-signal-long/30":e.conviction>=3?"bg-accent-blue/15 text-accent-blue border-accent-blue/30":"bg-bg-elevated text-text-muted border-border"}`,title:`Conviction: ${e.conviction}/10`,children:e.conviction})]}),r.jsx("button",{onClick:l,disabled:a,className:"opacity-70 sm:opacity-0 sm:group-hover:opacity-100 p-1 rounded text-text-muted hover:text-signal-short transition-all shrink-0 active:scale-90",title:"Remove pair",children:r.jsx(Et,{size:13})})]}),r.jsxs("div",{className:"flex items-center justify-between pl-4 text-[10px]",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsxs("span",{className:`flex items-center gap-0.5 font-mono ${s.on_binance?"text-signal-long font-medium":"text-text-muted/40"}`,title:`Binance: ${s.on_binance?"Available":"Unavailable"}`,children:[s.on_binance?"✓":"○"," Bin"]}),r.jsxs("span",{className:`flex items-center gap-0.5 font-mono ${s.on_bybit?"text-signal-long font-medium":"text-text-muted/40"}`,title:`Bybit: ${s.on_bybit?"Available":"Unavailable"}`,children:[s.on_bybit?"✓":"○"," Byb"]}),r.jsxs("span",{className:`flex items-center gap-0.5 font-mono ${s.on_okx?"text-signal-long font-medium":"text-text-muted/40"}`,title:`OKX: ${s.on_okx?"Available":"Unavailable"}`,children:[s.on_okx?"✓":"○"," OKX"]}),r.jsxs("span",{className:`flex items-center gap-0.5 font-mono ${s.on_bitget?"text-signal-long font-medium":"text-text-muted/40"}`,title:`Bitget: ${s.on_bitget?"Available":"Unavailable"}`,children:[s.on_bitget?"✓":"○"," Bit"]}),r.jsxs("span",{className:`flex items-center gap-0.5 font-mono ${s.on_hyperliquid?"text-signal-long font-medium":"text-text-muted/40"}`,title:`Hyperliquid: ${s.on_hyperliquid?"Available":"Unavailable"}`,children:[s.on_hyperliquid?"✓":"○"," HL"]})]}),e&&e.has_spot===!0&&r.jsx("span",{className:"text-[9px] font-mono text-emerald-400 font-medium shrink-0 ml-1",children:"🛡️ Spot"}),e&&e.has_spot===!1&&r.jsx("span",{className:"text-[9px] font-mono text-amber-400 font-bold shrink-0 ml-1",children:"⚠️ Perp"})]})]})}function Ka(...s){return ps(ms(s))}const rh={sm:"w-4 h-4 border-2",md:"w-6 h-6 border-2",lg:"w-10 h-10 border-3"};function nn({size:s="md",className:e}){return r.jsx("div",{className:Ka("rounded-full border-accent-blue border-t-transparent animate-spin",rh[s],e)})}function Re({className:s}){return r.jsx("div",{className:Ka("skeleton",s)})}function nh(){return r.jsxs("div",{className:"card p-5 space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx(Re,{className:"h-5 w-24"}),r.jsx(Re,{className:"h-6 w-16 rounded-full"})]}),r.jsx(Re,{className:"h-4 w-32"}),r.jsx(Re,{className:"h-3 w-full rounded-full"}),r.jsx("div",{className:"space-y-2",children:[...Array(4)].map((s,e)=>r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx(Re,{className:"h-3 w-28"}),r.jsx(Re,{className:"h-3 w-16"})]},e))})]})}function ah({pairs:s,signals:e,isLoading:t,selectedSymbol:i,onSelect:n}){const a=new Map(e.map(c=>[c.symbol,c]));if(t)return r.jsx("div",{className:"space-y-2 px-2",children:[...Array(4)].map((c,d)=>r.jsxs("div",{className:"space-y-1.5 px-3 py-2.5",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Re,{className:"w-2 h-2 rounded-full"}),r.jsx(Re,{className:"h-4 flex-1"})]}),r.jsx(Re,{className:"h-3 w-28 ml-4"})]},d))});if(s.length===0)return r.jsx("div",{className:"px-3 py-4 text-center",children:r.jsx("p",{className:"text-xs text-text-muted",children:"No pairs added yet"})});const o=[...s.filter(c=>c.is_active)].sort((c,d)=>c.symbol.localeCompare(d.symbol)),l=s.filter(c=>!c.is_active);return r.jsxs("div",{className:"space-y-1 px-2",children:[o.map(c=>r.jsx(Hs,{pair:c,signal:a.get(c.symbol),isSelected:i===c.symbol,onSelect:n},c.id)),l.length>0&&r.jsxs(r.Fragment,{children:[o.length>0&&r.jsx("div",{className:"px-3 pt-3 pb-1",children:r.jsx("p",{className:"text-[10px] uppercase tracking-widest text-text-muted font-medium",children:"Inactive"})}),l.map(c=>r.jsx(Hs,{pair:c,signal:a.get(c.symbol),isSelected:i===c.symbol,onSelect:n},c.id))]})]})}function oh(...s){return ps(ms(s))}const lh={primary:"bg-accent-blue hover:bg-blue-600 text-white border-transparent",ghost:"bg-transparent hover:bg-bg-elevated text-text-secondary hover:text-text-primary border-border",danger:"bg-transparent hover:bg-signal-short-bg text-signal-short border-signal-short/30 hover:border-signal-short/60",success:"bg-transparent hover:bg-signal-long-bg text-signal-long border-signal-long/30 hover:border-signal-long/60"},ch={sm:"text-xs px-2.5 py-1.5 gap-1",md:"text-sm px-4 py-2 gap-2",lg:"text-base px-5 py-2.5 gap-2"};function se({variant:s="ghost",size:e="md",loading:t=!1,icon:i,children:n,className:a,disabled:o,...l}){return r.jsxs("button",{className:oh("inline-flex items-center justify-center font-medium rounded-lg border","transition-colors duration-150 cursor-pointer","disabled:opacity-50 disabled:cursor-not-allowed",lh[s],ch[e],a),disabled:o||t,...l,children:[t?r.jsx("span",{className:"w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"}):i||null,n]})}const dh=y.lazy(()=>xt(()=>import("./AddPairModal-DCQtFcNW.js"),__vite__mapDeps([0,1,2,3])).then(s=>({default:s.AddPairModal})));function hh({pairs:s,signals:e,isLoading:t,selectedSymbol:i,onSelect:n}){const[a,o]=y.useState(!1),l=s.filter(c=>c.is_active).length;return r.jsxs(r.Fragment,{children:[r.jsxs("aside",{className:"w-64 lg:w-72 xl:w-80 shrink-0 flex flex-col border-r border-border bg-bg-card overflow-hidden",children:[r.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(na,{size:14,className:"text-accent-blue"}),r.jsx("span",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wider",children:"Pairs"})]}),l>0&&r.jsxs("span",{className:"text-[10px] font-mono bg-accent-blue/10 text-accent-blue border border-accent-blue/20 px-1.5 py-0.5 rounded",children:[l," active"]})]}),r.jsx(se,{variant:"primary",size:"sm",onClick:()=>o(!0),icon:r.jsx(lr,{size:13}),className:"w-full justify-center",children:"Add Pair"})]}),r.jsx("div",{className:"flex-1 overflow-y-auto py-2",children:r.jsx(ah,{pairs:s,signals:e,isLoading:t,selectedSymbol:i,onSelect:n})}),r.jsx("div",{className:"px-4 py-3 border-t border-border",children:r.jsx("div",{className:"grid grid-cols-3 gap-2 text-center",children:["LONG","SHORT","NEUTRAL"].map(c=>{const d=new Set(s.filter(u=>u.is_active).map(u=>u.symbol)),h=e.filter(u=>d.has(u.symbol)&&u.direction===c).length;return r.jsxs("div",{children:[r.jsx("p",{className:`text-sm font-bold font-mono ${c==="LONG"?"text-signal-long":c==="SHORT"?"text-signal-short":"text-text-muted"}`,children:h}),r.jsx("p",{className:"text-[10px] text-text-muted",children:c})]},c)})})})]}),a&&r.jsx(y.Suspense,{fallback:null,children:r.jsx(dh,{isOpen:a,onClose:()=>o(!1)})})]})}function uh({isOpen:s,onClose:e,pairs:t,signals:i,isLoading:n,selectedSymbol:a,onSelect:o,onOpenAddModal:l}){const[c,d]=y.useState("");if(!s)return null;const h=new Map(i.map(g=>[g.symbol,g])),u=t.filter(g=>g.is_active).length,m=t.filter(g=>g.symbol.toLowerCase().includes(c.toLowerCase().trim())),x=[...m.filter(g=>g.is_active)].sort((g,p)=>g.symbol.localeCompare(p.symbol)),b=m.filter(g=>!g.is_active),f=g=>{o(g),e()};return r.jsxs("div",{className:"fixed inset-0 z-50 md:hidden flex",children:[r.jsx("div",{className:"fixed inset-0 bg-black/80 backdrop-blur-sm transition-opacity",onClick:e}),r.jsxs("div",{className:"relative w-4/5 max-w-xs h-full bg-bg-card border-r border-border shadow-2xl flex flex-col z-10 animate-fade-in",children:[r.jsxs("div",{className:"p-4 border-b border-border space-y-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(na,{size:16,className:"text-accent-blue"}),r.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Trading Pairs"}),u>0&&r.jsxs("span",{className:"text-[10px] font-mono bg-accent-blue/15 text-accent-blue border border-accent-blue/30 px-1.5 py-0.5 rounded font-semibold",children:[u," Aktif"]})]}),r.jsx("button",{onClick:e,className:"p-1 rounded-lg text-text-secondary hover:text-text-primary hover:bg-bg-elevated transition-colors",children:r.jsx(Et,{size:18})})]}),a&&r.jsxs("button",{onClick:()=>f(null),className:"w-full flex items-center justify-center gap-1.5 py-1.5 px-3 rounded-lg bg-accent-blue/10 border border-accent-blue/30 text-xs font-semibold text-accent-blue hover:bg-accent-blue/20 transition-colors",children:[r.jsx(Xs,{size:13}),r.jsx("span",{children:"Tampilkan Semua Pair (Reset Filter)"})]}),r.jsxs("div",{className:"relative",children:[r.jsx(Zs,{size:14,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-text-muted pointer-events-none"}),r.jsx("input",{type:"text",placeholder:"Cari pair (e.g. BTC, ETH)...",value:c,onChange:g=>d(g.target.value),className:"input-field w-full pl-8 pr-3 py-1.5 text-xs font-mono"}),c&&r.jsx("button",{onClick:()=>d(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary",children:r.jsx(Et,{size:12})})]}),r.jsx(se,{variant:"primary",size:"sm",onClick:()=>{e(),l()},icon:r.jsx(lr,{size:14}),className:"w-full justify-center text-xs h-8",children:"Tambah Pair Baru"})]}),r.jsx("div",{className:"flex-1 overflow-y-auto py-2 custom-scrollbar",children:n?r.jsx("div",{className:"space-y-2 px-3",children:[...Array(5)].map((g,p)=>r.jsx("div",{className:"space-y-1.5 py-2",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Re,{className:"w-2 h-2 rounded-full"}),r.jsx(Re,{className:"h-4 flex-1"})]})},p))}):m.length===0?r.jsx("div",{className:"p-4 text-center",children:r.jsx("p",{className:"text-xs text-text-muted",children:c?`Tidak ada pair "${c}"`:"Belum ada pair ditambahkan"})}):r.jsxs("div",{className:"space-y-1 px-2",children:[x.map(g=>r.jsx(Hs,{pair:g,signal:h.get(g.symbol),isSelected:a===g.symbol,onSelect:p=>f(p)},g.id)),b.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 pt-3 pb-1",children:r.jsx("p",{className:"text-[10px] uppercase tracking-widest text-text-muted font-medium",children:"Nonaktif"})}),b.map(g=>r.jsx(Hs,{pair:g,signal:h.get(g.symbol),isSelected:a===g.symbol,onSelect:p=>f(p)},g.id))]})]})}),r.jsx("div",{className:"p-3 border-t border-border bg-bg-primary/50 shrink-0",children:r.jsx("div",{className:"grid grid-cols-3 gap-2 text-center",children:["LONG","SHORT","NEUTRAL"].map(g=>{const p=new Set(t.filter(S=>S.is_active).map(S=>S.symbol)),v=i.filter(S=>p.has(S.symbol)&&S.direction===g).length;return r.jsxs("div",{children:[r.jsx("p",{className:`text-xs font-bold font-mono ${g==="LONG"?"text-signal-long":g==="SHORT"?"text-signal-short":"text-text-muted"}`,children:v}),r.jsx("p",{className:"text-[9px] text-text-muted font-medium",children:g})]},g)})})})]})]})}function mh(s,e){return e==="LONG"?s>=7?"from-emerald-500 to-green-400":s>=4?"from-yellow-500 to-amber-400":"from-gray-500 to-gray-400":e==="SHORT"?s>=7?"from-red-500 to-rose-400":s>=4?"from-orange-500 to-amber-400":"from-gray-500 to-gray-400":"from-gray-500 to-gray-400"}function ph(s,e){return e==="LONG"?s>=7?"text-signal-long":s>=4?"text-accent-yellow":"text-text-secondary":e==="SHORT"?s>=7?"text-signal-short":s>=4?"text-orange-400":"text-text-secondary":"text-text-secondary"}function fh(s){return s>=8?"Very High":s>=6?"High":s>=4?"Moderate":s>=2?"Low":"Very Low"}function xh({score:s,direction:e,showLabel:t=!0}){const i=Math.max(0,Math.min(10,s)),n=i/10*100,a=mh(i,e),o=ph(i,e);return r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-xs text-text-secondary font-medium",children:"Conviction"}),r.jsxs("div",{className:"flex items-center gap-2",children:[t&&r.jsx("span",{className:"text-xs text-text-secondary",children:fh(i)}),r.jsx("span",{className:`font-mono font-bold text-lg leading-none ${o}`,children:i.toFixed(1)}),r.jsx("span",{className:"text-xs text-text-muted",children:"/10"})]})]}),r.jsxs("div",{className:"relative h-2 bg-bg-elevated rounded-full overflow-hidden border border-border",children:[r.jsx("div",{className:`absolute inset-y-0 left-0 rounded-full bg-gradient-to-r ${a} transition-all duration-700 ease-out`,style:{width:`${n}%`}}),[3,6,9].map(l=>r.jsx("div",{className:"absolute inset-y-0 w-px bg-bg-primary/50",style:{left:`${l/10*100}%`}},l))]}),r.jsxs("div",{className:"flex justify-between text-[10px] text-text-muted font-mono",children:[r.jsx("span",{children:"0"}),r.jsx("span",{children:"5"}),r.jsx("span",{children:"10"})]})]})}const bh=[{key:"funding_rate",icon:"📊",label:"Funding Rate",getValue:s=>{const e=s.funding_rate.value;return e==null||isNaN(e)?"N/A":`${e>=0?"+":""}${(e*100).toFixed(4)}%`},getScore:s=>s.funding_rate.score},{key:"oi_divergence",icon:"📈",label:"OI Divergence",getValue:s=>{const e=String(s.oi_divergence.value||"Neutral"),t=s.oi_divergence.oi_change_4h_pct;return t!=null&&!isNaN(t)&&Math.abs(t)>=.05?`${e} | 4H OI: ${t>=0?"+":""}${t.toFixed(2)}%`:e},getScore:s=>s.oi_divergence.score},{key:"cvd",icon:"💹",label:"Futures CVD",getValue:s=>{const e=s.cvd.value;return typeof e=="number"?Math.abs(e)>=1e6?`${(e/1e6).toFixed(2)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1)}K`:e.toFixed(2):String(e)},getScore:s=>s.cvd.score},{key:"spot_futures_cvd",icon:"🏆",label:"Spot vs Fut CVD",getValue:s=>String(s.spot_futures_cvd?.value||"Futures Only"),getScore:s=>s.spot_futures_cvd?.score??0},{key:"hyperliquid",icon:"⚡",label:"Hyperliquid DEX",getValue:s=>String(s.hyperliquid?.value||"N/A"),getScore:s=>s.hyperliquid?.score??0},{key:"cross_exchange",icon:"🔀",label:"3-Way Consensus",getValue:s=>{const e=s.cross_exchange.divergence_pct;return e==null||isNaN(e)?"0.000%":`${e.toFixed(3)}%`},getScore:s=>s.cross_exchange.score},{key:"ls_ratio",icon:"👥",label:"L/S Ratio",getValue:s=>{const e=s.ls_ratio.whale_position_long_ratio,t=s.ls_ratio.retail,i=s.ls_ratio.smart_money_delta;if(e!=null&&!isNaN(e)&&t!=null&&!isNaN(t)){const a=i!=null&&!isNaN(i)?` (Δ${i>=0?"+":""}${(i*100).toFixed(1)}%)`:"";return`Whale ${(e*100).toFixed(1)}%L vs Retail ${(t*100).toFixed(1)}%L${a}`}const n=s.ls_ratio.top_trader;return n==null||isNaN(n)?"N/A":`${(n*100).toFixed(1)}% Long`},getScore:s=>s.ls_ratio.score},{key:"basis",icon:"📐",label:"Basis",getValue:s=>{const e=s.basis?.value;if(e==null)return"N/A";const t=Number(e);return isNaN(t)?String(e):`${t>=0?"+":""}${t.toFixed(4)}%`},getScore:s=>s.basis?.score??0},{key:"market_structure",icon:"🏗️",label:"Market Structure",getValue:s=>{const e=s.market_structure,t=e?.tf?String(e.tf).toUpperCase():"1H";return`${e?.structure||"Ranging"} (${t})`},getScore:s=>s.market_structure?.score??0},{key:"orderbook_skew",icon:"📚",label:"Orderbook Skew",getValue:s=>String(s.orderbook_skew?.value||s.orderbook_skew?.label||"Balanced"),getScore:s=>s.orderbook_skew?.score??0},{key:"whale_order_flow",icon:"🐋",label:"Whale Block Flow",getValue:s=>String(s.whale_order_flow?.value||s.whale_order_flow?.label||"Balanced"),getScore:s=>s.whale_order_flow?.score??0},{key:"fake_detector",icon:"⚠️",label:"Fake Detector",getValue:s=>{const e=s.fake_detector;return e&&e.warnings&&e.warnings.length>0?`${e.warnings.length} warning${e.warnings.length!==1?"s":""}`:"Clean"},getScore:s=>s.fake_detector?.score??0}];function gh({score:s}){return s>0?r.jsx("span",{className:"w-2 h-2 rounded-full bg-signal-long inline-block"}):s<0?r.jsx("span",{className:"w-2 h-2 rounded-full bg-signal-short inline-block"}):r.jsx("span",{className:"w-2 h-2 rounded-full bg-text-muted inline-block"})}function vh({score:s}){return s===0?r.jsx("span",{className:"font-mono text-xs text-text-muted",children:"[0]"}):s>0?r.jsxs("span",{className:"font-mono text-xs text-signal-long",children:["[+",s,"]"]}):r.jsxs("span",{className:"font-mono text-xs text-signal-short",children:["[",s,"]"]})}function yh({signals:s,predictive:e}){return r.jsxs("div",{className:"space-y-1",children:[bh.map(t=>{const i=t.getValue(s),n=t.getScore(s);return r.jsxs("div",{className:"flex items-center gap-3 py-2 px-3 rounded-lg hover:bg-bg-elevated transition-colors group",children:[r.jsx("span",{className:"text-sm w-5 shrink-0",children:t.icon}),r.jsx("span",{className:"text-[11px] sm:text-xs text-text-secondary w-24 sm:w-32 shrink-0 font-medium",children:t.label}),r.jsx("span",{className:"font-mono text-xs text-text-primary flex-1 min-w-0 break-words leading-tight",children:i}),r.jsx(vh,{score:n}),r.jsx(gh,{score:n})]},t.key)}),s.market_structure?.structure_per_tf&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-border",children:[r.jsx("p",{className:"text-[11px] font-semibold text-text-secondary uppercase tracking-wider mb-2",children:"Multi-Timeframe Structure (1D ➔ 5M)"}),r.jsx("div",{className:"grid grid-cols-5 gap-1.5 text-center font-mono",children:["1d","4h","1h","15m","5m"].map(t=>{const i=s.market_structure?.structure_per_tf?.[t]||"unknown",n=i==="bullish",a=i==="bearish",o=s.market_structure?.tf?.toLowerCase()===t;return r.jsxs("div",{className:`py-1.5 px-1 rounded-md border text-xs flex flex-col items-center justify-center ${o?"ring-1 ring-accent-blue font-bold":""} ${n?"bg-signal-long/10 border-signal-long/30 text-signal-long":a?"bg-signal-short/10 border-signal-short/30 text-signal-short":"bg-bg-elevated border-border text-text-muted"}`,children:[r.jsx("span",{className:"text-[10px] text-text-muted uppercase font-bold",children:t}),r.jsx("span",{className:"text-[10px] truncate max-w-full font-medium",children:n?"▲ BULL":a?"▼ BEAR":"━ CHOP"})]},t)})})]}),e&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-border",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("p",{className:"text-[11px] font-semibold text-accent-blue uppercase tracking-wider",children:"🔮 Forward Anticipation & Liquidity Pools"}),e.volatility_squeeze?.is_squeeze&&r.jsx("span",{className:"text-[10px] font-mono text-amber-400 font-bold",children:"⚡ Squeeze Active"})]}),r.jsxs("div",{className:"space-y-2 text-xs",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{className:"p-2 rounded-lg bg-bg-elevated border border-border",children:[r.jsx("span",{className:"text-[9px] text-text-muted uppercase block font-medium",children:"Short Liq Pool (Upper Magnet)"}),r.jsxs("span",{className:"font-mono font-bold text-signal-short",children:[e.liquidation_magnets?.upper_magnet_str||"-"," ",r.jsxs("span",{className:"text-[10px] font-normal text-text-secondary",children:["(",e.liquidation_magnets?.dist_upper_pct!=null?`${e.liquidation_magnets.dist_upper_pct>0?"+":""}${e.liquidation_magnets.dist_upper_pct}%`:"-",")"]})]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-elevated border border-border",children:[r.jsx("span",{className:"text-[9px] text-text-muted uppercase block font-medium",children:"Long Liq Pool (Lower Magnet)"}),r.jsxs("span",{className:"font-mono font-bold text-signal-long",children:[e.liquidation_magnets?.lower_magnet_str||"-"," ",r.jsxs("span",{className:"text-[10px] font-normal text-text-secondary",children:["(",e.liquidation_magnets?.dist_lower_pct!=null?`${e.liquidation_magnets.dist_lower_pct}%`:"-",")"]})]})]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-elevated/70 border border-border flex flex-col gap-1 text-[11px]",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("span",{className:"text-text-secondary",children:["Resting Depth Skew",e.orderbook_skew?.venues_count&&e.orderbook_skew.venues_count>1?` (${e.orderbook_skew.venues_count} Bursa)`:"",":"]}),r.jsx("span",{className:"font-mono font-semibold text-text-primary",children:e.orderbook_skew?.resting_pressure||"BALANCED RESTING DEPTH"})]}),e.orderbook_skew&&(e.orderbook_skew.bid_depth_usd>0||e.orderbook_skew.ask_depth_usd>0)&&r.jsxs("div",{className:"flex items-center justify-between text-[10px] font-mono pt-1 border-t border-border/40",children:[r.jsxs("span",{className:"text-emerald-400 font-medium",children:["Bids: ",e.orderbook_skew.bid_depth_usd>=1e6?`$${(e.orderbook_skew.bid_depth_usd/1e6).toFixed(2)}M`:e.orderbook_skew.bid_depth_usd>=1e3?`$${(e.orderbook_skew.bid_depth_usd/1e3).toFixed(1)}K`:`$${e.orderbook_skew.bid_depth_usd.toFixed(0)}`]}),r.jsx("span",{className:"text-text-muted",children:"vs"}),r.jsxs("span",{className:"text-rose-400 font-medium",children:["Asks: ",e.orderbook_skew.ask_depth_usd>=1e6?`$${(e.orderbook_skew.ask_depth_usd/1e6).toFixed(2)}M`:e.orderbook_skew.ask_depth_usd>=1e3?`$${(e.orderbook_skew.ask_depth_usd/1e3).toFixed(1)}K`:`$${e.orderbook_skew.ask_depth_usd.toFixed(0)}`]})]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-elevated/70 border border-border flex items-center justify-between text-[11px]",children:[r.jsx("span",{className:"text-text-secondary",children:"Volatility State:"}),r.jsx("span",{className:"font-mono font-semibold text-amber-400 truncate ml-2",children:e.volatility_squeeze?.label||"Kondisi Volatilitas Rata-Rata"})]})]})]}),s.fake_detector?.is_fake&&s.fake_detector?.warnings?.length>0&&r.jsxs("div",{className:"mt-2 p-3 rounded-lg bg-signal-short-bg border border-signal-short/20",children:[r.jsx("p",{className:"text-xs text-signal-short font-semibold mb-1.5",children:"⚠️ Fake Signal Detected"}),r.jsx("ul",{className:"space-y-0.5",children:s.fake_detector.warnings.map((t,i)=>r.jsxs("li",{className:"text-xs text-text-secondary flex gap-1.5",children:[r.jsx("span",{className:"text-signal-short",children:"•"})," ",t]},i))})]})]})}function wh(s){return s==null||isNaN(s)?"N/A":s>=1e9?`$${(s/1e9).toFixed(2)}B`:s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${s.toLocaleString("en-US",{maximumFractionDigits:0})}`}function Nh(s){return s==null||isNaN(s)?"N/A":`${s>=0?"+":""}${(s*100).toFixed(4)}%`}function jh(s){return s==null||isNaN(s)?"N/A":s>=1e3?`$${s.toLocaleString("en-US",{maximumFractionDigits:2})}`:s>=1?`$${s.toFixed(4)}`:s>=.01?`$${s.toFixed(6)}`:`$${s.toFixed(8)}`}function Wt({name:s,logo:e,funding_rate:t,oi:i,mark_price:n}){const a=t!=null?t<0?"text-signal-long":t>0?"text-signal-short":"text-text-secondary":"text-text-muted";return r.jsxs("div",{className:"flex items-center gap-3 py-2",children:[r.jsxs("div",{className:"flex items-center gap-2 w-20 shrink-0",children:[r.jsx("span",{className:"text-base",children:e}),r.jsx("span",{className:"text-xs font-semibold text-text-secondary",children:s})]}),r.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-1.5 sm:gap-2 min-w-0",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-[9px] sm:text-[10px] text-text-muted uppercase tracking-wide",children:"Funding"}),r.jsx("p",{className:`font-mono text-[11px] sm:text-xs font-semibold truncate ${a}`,children:Nh(t)})]}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-[9px] sm:text-[10px] text-text-muted uppercase tracking-wide",children:"Open Int."}),r.jsx("p",{className:"font-mono text-[11px] sm:text-xs text-text-primary truncate",children:wh(i)})]}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-[9px] sm:text-[10px] text-text-muted uppercase tracking-wide",children:"Mark Price"}),r.jsx("p",{className:"font-mono text-[11px] sm:text-xs text-text-primary truncate",children:jh(n)})]})]})]})}function _h({exchangeData:s}){return!!!(s&&(s.binance||s.bybit||s.okx||s.bitget||s.hyperliquid))||!s?r.jsx("div",{className:"py-3 text-center text-xs text-text-muted",children:"No exchange data available"}):r.jsxs("div",{className:"divide-y divide-border",children:[s.binance&&r.jsx(Wt,{name:"Binance",logo:"🟡",...s.binance}),s.bybit&&r.jsx(Wt,{name:"Bybit",logo:"🟠",...s.bybit}),s.okx&&r.jsx(Wt,{name:"OKX",logo:"🔵",...s.okx}),s.bitget&&r.jsx(Wt,{name:"Bitget",logo:"🟢",...s.bitget}),s.hyperliquid&&r.jsx(Wt,{name:"Hyperliquid",logo:"⚡",...s.hyperliquid})]})}function Sh(...s){return ps(ms(s))}const kh={long:"bg-signal-long-bg text-signal-long border border-signal-long/30",short:"bg-signal-short-bg text-signal-short border border-signal-short/30",neutral:"bg-signal-neutral-bg text-text-secondary border border-border",blue:"bg-blue-500/10 text-accent-blue border border-accent-blue/30",yellow:"bg-yellow-500/10 text-accent-yellow border border-accent-yellow/30"};function Mh({variant:s="neutral",size:e="sm",children:t,className:i}){return r.jsx("span",{className:Sh("inline-flex items-center gap-1 font-mono font-semibold rounded-md",e==="sm"?"text-xs px-2 py-0.5":"text-sm px-2.5 py-1",kh[s],i),children:t})}const oi={getAll:async()=>{const{data:s}=await ie.get("/api/signals");return s},getBySymbol:async s=>{const{data:e}=await ie.get(`/api/signals/${s}/latest`);return e},getAccuracy:async(s=30,e)=>{const{data:t}=await ie.get("/api/signals/accuracy",{params:e?{days:s,symbol:e}:{days:s}});return t},refresh:async s=>{const{data:e}=await ie.post(`/api/signals/${s}/refresh`);return e},refreshAll:async()=>{const{data:s}=await ie.post("/api/signals/refresh-all");return s}},ht=["signals"];function li(){const s=!!Qe();return Zt({queryKey:ht,queryFn:oi.getAll,placeholderData:e=>e,refetchInterval:()=>Qe()?3e4:6e3,refetchOnWindowFocus:!1,retry:2,staleTime:s?15e3:4e3})}function Ga(){const s=os();return as({mutationFn:e=>oi.refresh(e),onSuccess:e=>{s.setQueryData([...ht,e.symbol],e),s.invalidateQueries({queryKey:ht})}})}function Ch(){const s=os();return as({mutationFn:()=>oi.refreshAll(),onSuccess:e=>{e?.signals&&s.setQueryData(ht,e.signals),s.invalidateQueries({queryKey:ht})}})}const Eh=y.lazy(()=>xt(()=>import("./AIAnalysisPanel-DsgKGe3C.js"),__vite__mapDeps([4,1,2,3])).then(s=>({default:s.AIAnalysisPanel})));function Th(s){if(!s)return"just now";const e=new Date(s).getTime();if(!Number.isFinite(e))return"just now";const t=Date.now()-e,i=Math.max(0,Math.floor(t/1e3));if(i<60)return`${i}s ago`;const n=Math.floor(i/60);if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function vs(s){return!s||isNaN(s)||s<=0?"$0":s>=1e6?`$${(s/1e6).toFixed(2)}M`:s>=1e3?`$${(s/1e3).toFixed(1)}K`:`$${s.toFixed(0)}`}const Rh={LONG:"glow-long border-signal-long/20",SHORT:"glow-short border-signal-short/20",NEUTRAL:"border-border"},an={LONG:"animate-pulse-green",SHORT:"animate-pulse-red"};function Ph({signal:s,onNavigateToAI:e,onNavigateToChart:t}){const[i,n]=y.useState(!1),[a,o]=y.useState(!1),[l,c]=y.useState(!1),[d,h]=y.useState(!1),[u,m]=y.useState(()=>!s.veto_reason&&s.horizons?.intraday?.direction==="NEUTRAL"&&s.horizons?.swing?.direction&&s.horizons.swing.direction!=="NEUTRAL"?"swing":"intraday"),{mutate:x,isPending:b}=Ga(),{toast:f}=bt();y.useEffect(()=>{h(!0);const z=setTimeout(()=>h(!1),900);return()=>clearTimeout(z)},[s.updated_at]),y.useEffect(()=>{const z=s.horizons?.intraday?.direction,V=s.horizons?.swing?.direction;!s.veto_reason&&z==="NEUTRAL"&&V&&V!=="NEUTRAL"?m("swing"):(s.veto_reason||z&&z!=="NEUTRAL")&&m("intraday")},[s.veto_reason,s.horizons?.intraday?.direction,s.horizons?.swing?.direction]);const g=()=>{x(s.symbol,{onSuccess:()=>f(`${s.symbol} refreshed`,"success"),onError:z=>f(z.message,"error")})},p=s.horizons?s.horizons[u]:void 0,v=p?.direction??s.direction,S=p?.conviction??s.conviction,j=p?.action||s.action,k=p?.quick_verdict||s.quick_verdict,C=p?p.trade_levels:s.trade_levels,E=C?.squeeze_intensity==="EXTREME SQUEEZE"||C?.squeeze_intensity==="MODERATE SQUEEZE",T=s.predictive?.orderbook_skew,D=T?.bid_depth_usd??0,O=T?.ask_depth_usd??0,M=D+O,R=M>0?Math.round(D/M*100):50,L=M>0?100-R:50,$=z=>{z.stopPropagation();const V=v==="LONG",q=`⚡ PERPS AI: ${s.symbol} ${v} (${p?.timeframe||s.active_timeframe}) +Action: ${j||(V?"BUY":"SELL")} +Conviction: ${S}/10 +${C?`Entry Zone: ${C.entry_zone} +Stop Loss: ${C.stop_loss_str} +Take Profit 1: ${C.take_profit_1_str} +Take Profit 2: ${C.take_profit_2_str} +🎯 Magnet Target: ${C.predicted_target||"N/A"} +R:R: ${C.risk_reward}`:""} +Verdict: ${k||""} +Forward Anticipation: ${s.anticipation||C?.anticipation||""}`;navigator.clipboard.writeText(q),o(!0),f(`${s.symbol} plan copied!`,"success"),setTimeout(()=>o(!1),2e3)};return r.jsxs("div",{className:`card border transition-all duration-300 flex flex-col justify-between signal-card-container overflow-hidden rounded-xl ${d?"ring-1 ring-accent-blue/50":""} ${s.has_spot===!1?"border-amber-500/30 hover:border-amber-500/50":"border-border hover:border-border/80"} ${Rh[s.direction]}`,children:[r.jsxs("div",{className:"p-3.5 sm:p-4 flex flex-col flex-1 justify-between",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:`w-2.5 h-2.5 rounded-full shrink-0 ${s.direction==="LONG"?"bg-signal-long "+an.LONG:s.direction==="SHORT"?"bg-signal-short "+an.SHORT:"bg-text-muted"}`}),r.jsx("h3",{className:"text-sm sm:text-base font-bold font-mono text-text-primary leading-none truncate",children:s.symbol})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[s.streak&&s.streak>=2&&r.jsxs("span",{className:"text-[10px] font-mono font-bold px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-400 border border-amber-500/30 flex items-center gap-0.5 shrink-0 animate-pulse",title:`Consistent Conviction Streak: ${s.streak} cycles`,children:["🔥 ",s.streak,"x"]}),r.jsx(hr,{direction:s.direction,size:"sm"}),r.jsxs("span",{className:`text-[10px] font-mono font-bold px-1.5 py-0.5 rounded border ${s.conviction>=6?"bg-signal-long/15 text-signal-long border-signal-long/30":s.conviction>=3?"bg-accent-blue/15 text-accent-blue border-accent-blue/30":"bg-bg-elevated text-text-muted border-border"}`,title:`Conviction: ${s.conviction}/10`,children:[s.conviction,"/10"]})]})]}),r.jsxs("div",{className:"flex items-center justify-between gap-2 mb-3 text-[11px] text-text-secondary",children:[r.jsx("span",{className:"truncate capitalize",children:s.market_condition||"Normal Market"}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 flex-wrap justify-end",children:[s.sniper_grade==="SNIPER_A_PLUS"&&r.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 flex items-center gap-1",title:"Sniper A+: Intraday (15m-4H) & Swing (4H-1D) searah + Spot/Squeeze terkonfirmasi",children:[r.jsx(Xe,{size:10,className:"text-emerald-400"}),r.jsx("span",{children:"SNIPER A+"})]}),s.sniper_grade==="INTRADAY_ONLY"&&r.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-cyan-500/15 text-cyan-300 border border-cyan-500/35 flex items-center gap-1",title:"Intraday Setup (15m-4H)",children:r.jsx("span",{children:"⚡ INTRADAY"})}),s.sniper_grade==="SWING_SETUP"&&r.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-indigo-500/15 text-indigo-300 border border-indigo-500/35 flex items-center gap-1",title:"Swing Setup (4H-1D)",children:r.jsx("span",{children:"🌊 SWING"})}),s.sniper_grade==="SNIPER_COUNTER"&&r.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/40 flex items-center gap-1",title:"Counter-Trend: Intraday berlawanan dengan struktur Swing 4H-1D",children:r.jsx("span",{children:"⚠️ COUNTER"})}),s.liquidity_guard&&!s.liquidity_guard.passed&&r.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-rose-500/20 text-rose-300 border border-rose-500/40 flex items-center gap-1",title:`Spread ${s.liquidity_guard.spread_bps} bps | Depth ±1.5%: $${s.liquidity_guard.depth_usd.toLocaleString()}`,children:r.jsx("span",{children:"Thin Book"})}),s.has_spot===!1&&r.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-amber-500/15 text-amber-300 border border-amber-500/30 flex items-center gap-1",title:"Aset RAWAN BANDAR: Kontrak Perp-Only tanpa pasar Spot riil.",children:[r.jsx(ve,{size:10,className:"text-amber-400"}),r.jsx("span",{children:"Perp Only"})]}),s.has_spot===!0&&r.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/25 flex items-center gap-1",title:"Aset AMAN: Pasar Spot riil tersedia.",children:[r.jsx(Tt,{size:10,className:"text-emerald-400"}),r.jsx("span",{children:"Spot"})]}),s.breakout_radar?.is_breakout_primed?r.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono font-bold border flex items-center gap-1 ${s.breakout_radar.squeeze_stage==="READY_TO_BURST"?"bg-purple-500/25 text-purple-300 border-purple-500/50 animate-pulse":"bg-amber-500/20 text-amber-300 border-amber-500/40"}`,title:s.breakout_radar.catalyst_summary,children:[r.jsx(Oe,{size:10,className:"text-yellow-400"}),r.jsx("span",{children:s.breakout_radar.squeeze_stage==="READY_TO_BURST"?"BURST PRIMED":"COILING"})]}):E?r.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-amber-500/20 text-amber-400 border border-amber-500/30 flex items-center gap-1 animate-pulse",title:"Volatility Squeeze (Breakout Imminent)",children:[r.jsx(Oe,{size:10}),r.jsx("span",{children:"Squeeze"})]}):null,r.jsx(Mh,{variant:"blue",size:"sm",children:s.active_timeframe})]})]}),(s.quick_verdict||s.anticipation||s.has_spot===!1)&&r.jsxs("div",{className:`mb-3 p-2.5 rounded-lg border text-xs space-y-1.5 transition-colors ${s.has_spot===!1?"bg-amber-950/20 border-amber-500/30":"bg-bg-elevated/70 border-border/80"}`,children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("span",{className:`font-mono font-bold uppercase text-[9px] sm:text-[10px] px-1.5 py-0.5 rounded shrink-0 tracking-wide ${v==="LONG"?"bg-signal-long/20 text-signal-long border border-signal-long/30":v==="SHORT"?"bg-signal-short/20 text-signal-short border border-signal-short/30":s.breakout_radar?.is_breakout_primed?"bg-purple-500/25 text-purple-300 border border-purple-500/40 animate-pulse":"bg-bg-elevated text-text-muted border border-border"}`,children:j||(v==="LONG"?"BUY":v==="SHORT"?"SELL":"WAIT")}),r.jsx("p",{className:"text-[11px] sm:text-xs text-text-primary font-medium flex-1 leading-snug",children:k||(v==="LONG"?"Akumulasi beli dengan momentum tinggi":v==="SHORT"?"Tekanan jual terkonfirmasi":"Struktur pasar sideways/chop. Disarankan Wait-and-See.")})]}),s.anticipation&&s.anticipation!==s.quick_verdict&&r.jsxs("div",{className:"flex items-start gap-1.5 text-[10px] sm:text-[11px] text-accent-blue/90 pt-1 border-t border-border/40",children:[r.jsx("span",{className:"font-semibold shrink-0 uppercase font-mono tracking-wider text-[9px]",children:"🔮 Antisipasi:"}),r.jsx("span",{className:"text-text-secondary leading-snug",children:s.anticipation})]}),s.has_spot===!1&&r.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-amber-300/90 pt-1 border-t border-amber-500/20 font-medium",children:[r.jsx(ve,{size:11,className:"shrink-0 text-amber-400"}),r.jsx("span",{children:"Koin Perp-Only (tanpa spot). Wajib pasang SL ketat!"})]})]}),r.jsx(xh,{score:S,direction:v}),r.jsx("div",{className:"mt-2.5 p-2 rounded-lg bg-bg-elevated/40 border border-border/60",children:M>0?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-between text-[10px] font-mono mb-1",children:[r.jsxs("span",{className:"text-emerald-400 font-semibold flex items-center gap-1",children:[r.jsx("span",{children:"Bids"}),r.jsx("span",{className:"text-text-primary font-bold",children:vs(D)}),r.jsxs("span",{className:"text-text-muted text-[9px]",children:["(",R,"%)"]})]}),r.jsx("span",{className:"text-[9px] uppercase tracking-wider text-text-muted font-sans font-medium",title:T?.venues_count&&T.venues_count>1?`Likuiditas teragregasi dari ${T.venues_count} bursa (±1.5%)`:"Kedalaman orderbook ±1.5%",children:T?.venues_count&&T.venues_count>1?`Global Depth (${T.venues_count} Bursa)`:"Depth ±1.5%"}),r.jsxs("span",{className:"text-rose-400 font-semibold flex items-center gap-1",children:[r.jsxs("span",{className:"text-text-muted text-[9px]",children:["(",L,"%)"]}),r.jsx("span",{className:"text-text-primary font-bold",children:vs(O)}),r.jsx("span",{children:"Asks"})]})]}),r.jsxs("div",{className:"h-2 w-full bg-bg-card rounded-full overflow-hidden flex shadow-inner border border-border/30",children:[r.jsx("div",{className:"bg-emerald-500 h-full transition-all duration-500 rounded-l-full",style:{width:`${R}%`},title:`Bids (Beli): ${vs(D)} (${R}%)`}),r.jsx("div",{className:"bg-rose-500 h-full transition-all duration-500 rounded-r-full",style:{width:`${L}%`},title:`Asks (Jual): ${vs(O)} (${L}%)`})]}),r.jsxs("div",{className:"flex items-center justify-between mt-1 text-[9px] font-mono text-text-muted",children:[r.jsx("span",{className:R>=58?"text-emerald-400 font-bold":"",children:R>=65?"🛡️ Bid Wall Dominant":R>=55?"Buyers Ahead":"Buyers"}),r.jsx("span",{className:"text-text-secondary text-[9px]",children:T?.skew_ratio!==void 0?Math.abs(T.skew_ratio)<.05?"Skew: Balanced":`Skew: ${T.skew_ratio>0?"+":""}${(T.skew_ratio*100).toFixed(0)}%`:""}),r.jsx("span",{className:L>=58?"text-rose-400 font-bold":"",children:L>=65?"🛑 Ask Wall Dominant":L>=55?"Sellers Ahead":"Sellers"})]})]}):r.jsxs("div",{className:"flex items-center justify-between text-[10px] font-mono text-text-muted py-0.5",children:[r.jsxs("span",{className:"flex items-center gap-1.5 text-[9px] text-text-secondary",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"}),r.jsx("span",{children:"Order Book Depth:"}),r.jsx("span",{className:"text-text-muted italic",children:"Sinkronisasi antrean bursa..."})]}),r.jsx("span",{className:"text-[9px] text-accent-blue/80 font-sans",children:"Live Sync"})]})}),s.whale_flow&&(s.whale_flow.twap_bias&&s.whale_flow.twap_bias!=="NEUTRAL"||s.whale_flow.absorption_type&&s.whale_flow.absorption_type!=="NONE"||(s.whale_flow.sweep_buy_count||0)+(s.whale_flow.sweep_sell_count||0)>0||(s.whale_flow.onchain_whale_wallets||0)>0||Math.abs(s.whale_flow.smart_money_delta||0)>=.06)&&r.jsxs("div",{className:"mt-2 px-2 py-1.5 rounded-lg bg-bg-elevated/50 border border-border/60 flex flex-wrap items-center justify-between gap-1.5 text-[10px] font-mono",children:[r.jsxs("span",{className:"text-text-secondary font-semibold flex items-center gap-1",children:[r.jsx("span",{children:"🐋 Whale Radar:"}),(s.whale_flow.twap_bias==="ACCUMULATION"||s.whale_flow.twap_bias==="TWAP_BUY_ACCUMULATION"||s.whale_flow.twap_bias==="WHALE_TWAP_LONG_BUILDUP")&&r.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-emerald-500/15 text-emerald-300 border border-emerald-500/30 font-bold",children:["TWAP Accum (",(s.whale_flow.twap_buy_pct??55).toFixed(0),"% Buy)"]}),(s.whale_flow.twap_bias==="DISTRIBUTION"||s.whale_flow.twap_bias==="TWAP_SELL_DISTRIBUTION"||s.whale_flow.twap_bias==="WHALE_TWAP_SHORT_BUILDUP")&&r.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-rose-500/15 text-rose-300 border border-rose-500/30 font-bold",children:["TWAP Distrib (",(100-(s.whale_flow.twap_buy_pct??45)).toFixed(0),"% Sell)"]}),(s.whale_flow.absorption_type==="BULLISH_ICEBERG"||s.whale_flow.absorption_type==="BULLISH_ICEBERG_ABSORPTION")&&r.jsx("span",{className:"px-1.5 py-0.5 rounded bg-cyan-500/15 text-cyan-300 border border-cyan-500/30 font-bold",title:s.whale_flow.absorption_note||"Limit Bid Iceberg Absorption",children:"🧊 Bid Iceberg"}),(s.whale_flow.absorption_type==="BEARISH_ICEBERG"||s.whale_flow.absorption_type==="BEARISH_ICEBERG_ABSORPTION")&&r.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-300 border border-amber-500/30 font-bold",title:s.whale_flow.absorption_note||"Limit Ask Iceberg Absorption",children:"🧊 Ask Iceberg"})]}),r.jsxs("div",{className:"flex items-center gap-2 text-[9px] text-text-muted",children:[(s.whale_flow.sweep_buy_count||0)+(s.whale_flow.sweep_sell_count||0)>0&&r.jsxs("span",{title:"Reconstructed Aggressive Market Sweeps",children:["Sweeps:"," ",r.jsxs("strong",{className:"text-emerald-400",children:[s.whale_flow.sweep_buy_count||0,"B"]}),"/",r.jsxs("strong",{className:"text-rose-400",children:[s.whale_flow.sweep_sell_count||0,"S"]})]}),s.whale_flow.smart_money_delta!=null&&Math.abs(s.whale_flow.smart_money_delta)>=.06&&r.jsxs("span",{className:s.whale_flow.smart_money_delta>0?"text-emerald-400 font-bold":"text-rose-400 font-bold",title:"Top Whale Position Ratio vs Global Retail Account Ratio",children:["SmartΔ ",s.whale_flow.smart_money_delta>0?"+":"",(s.whale_flow.smart_money_delta*100).toFixed(0),"%"]}),(s.whale_flow.onchain_whale_wallets||0)>0&&r.jsxs("span",{className:"text-purple-300 font-bold",title:"Hyperliquid On-Chain Whale Wallets",children:["HL Wallets: ",s.whale_flow.onchain_whale_wallets]})]})]}),s.horizons&&r.jsx("div",{className:"mt-2.5 flex items-center justify-between gap-1.5 p-1 rounded-lg bg-bg-elevated/60 border border-border/60 text-[10px] font-mono",children:["intraday","swing"].map(z=>{const V=s.horizons?.[z];if(!V)return null;const q=u===z,Z=V.direction==="LONG"?"text-signal-long":V.direction==="SHORT"?"text-signal-short":"text-text-muted";return r.jsxs("button",{type:"button",onClick:()=>m(z),className:`flex-1 py-1 px-2 rounded-md flex items-center justify-between transition-all ${q?"bg-bg-card text-text-primary border border-border shadow-sm font-bold":"text-text-muted hover:text-text-secondary"}`,children:[r.jsx("span",{children:z==="intraday"?"⚡ 15m-4H":"🌊 4H-1D"}),r.jsxs("span",{className:Z,children:[V.direction," (",V.conviction,"/10)"]})]},z)})}),C&&r.jsxs("div",{className:`mt-3 p-2.5 rounded-lg border flex flex-col gap-2 ${s.has_spot===!1?"bg-amber-950/15 border-amber-500/25":"bg-bg-primary/80 border-border/70"}`,children:[r.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono border-b border-border/40 pb-1.5 gap-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[r.jsx("span",{className:"text-[9px] uppercase font-bold tracking-wider text-text-muted shrink-0",children:"ENTRY:"}),r.jsx("span",{className:"font-bold text-text-primary text-[11px] whitespace-normal",children:C.entry_zone})]}),r.jsxs("button",{onClick:$,title:"Copy Trade Plan",className:"px-2 py-0.5 rounded-md hover:bg-bg-elevated border border-border/60 hover:border-border text-text-muted hover:text-text-primary transition-all shrink-0 flex items-center gap-1 text-[10px] font-mono active:scale-95",children:[a?r.jsx(at,{size:11,className:"text-signal-long"}):r.jsx(es,{size:11}),r.jsx("span",{children:a?"Copied":"Plan"})]})]}),r.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 font-mono text-[10px] sm:text-[11px]",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-[8px] sm:text-[9px] uppercase tracking-wider text-signal-short block font-semibold",children:"SL"}),r.jsx("span",{className:"font-bold text-signal-short block whitespace-nowrap",children:C.stop_loss_str})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-[8px] sm:text-[9px] uppercase tracking-wider text-signal-long block font-semibold",children:"TP1"}),r.jsx("span",{className:"font-bold text-signal-long block whitespace-nowrap",children:C.take_profit_1_str})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-[8px] sm:text-[9px] uppercase tracking-wider text-signal-long/80 block font-semibold",children:"TP2"}),r.jsx("span",{className:"font-bold text-signal-long/90 block whitespace-nowrap",children:C.take_profit_2_str||"—"})]}),C.predicted_target?r.jsxs("div",{children:[r.jsxs("span",{className:"text-[8px] sm:text-[9px] uppercase tracking-wider text-amber-400 flex items-center gap-0.5 font-semibold",children:[r.jsx(Xe,{size:9})," Magnet"]}),r.jsx("span",{className:"font-bold text-amber-300 block whitespace-nowrap",children:C.predicted_target})]}):r.jsxs("div",{children:[r.jsx("span",{className:"text-[8px] sm:text-[9px] uppercase tracking-wider text-text-muted block font-semibold",children:"R:R"}),r.jsx("span",{className:"font-bold text-text-secondary block whitespace-nowrap",children:C.risk_reward})]})]})]})]}),r.jsxs("div",{className:"flex items-center justify-between gap-2 mt-3 pt-2.5 border-t border-border/40",children:[r.jsxs("div",{className:"flex items-center gap-1 text-[10px] sm:text-[11px] text-text-muted",children:[r.jsx(Fs,{size:11}),r.jsx("span",{children:Th(s.updated_at)})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[t&&r.jsxs("button",{onClick:()=>t(s.symbol),className:"px-2.5 py-1 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition-all shadow-sm active:scale-95 cursor-pointer border bg-sky-500/15 hover:bg-sky-500/25 border-sky-500/40 hover:border-sky-400 text-sky-300 hover:text-white",title:"Buka Live Chart & Order Flow Real-Time",children:[r.jsx(ot,{size:11,className:"text-sky-400"}),r.jsx("span",{children:"Chart"})]}),r.jsxs("button",{onClick:()=>{e?e(s.symbol):c(z=>!z)},className:"px-2.5 py-1 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition-all shadow-sm active:scale-95 cursor-pointer border bg-gradient-to-r from-purple-500/20 to-blue-500/20 hover:from-purple-500/30 hover:to-blue-500/30 border-purple-500/40 hover:border-purple-400 text-purple-300 hover:text-white",title:"Buka Halaman Tanya AI Khusus untuk Pair Ini",children:[r.jsx(Fe,{size:11,className:"text-purple-400 animate-pulse"}),r.jsx("span",{children:"Tanya AI"})]}),r.jsx(se,{variant:"ghost",size:"sm",onClick:g,loading:b,icon:r.jsx(Pe,{size:11}),className:"text-xs px-2 py-1 h-7",children:r.jsx("span",{className:"hidden xs:inline",children:"Refresh"})}),r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>n(z=>!z),icon:i?r.jsx(Us,{size:11}):r.jsx(_t,{size:11}),className:"text-xs px-2 py-1 h-7",children:i?"Hide":"Details"})]})]})]}),i&&r.jsxs("div",{className:"border-t border-border animate-fade-in",children:[r.jsxs("div",{className:"p-5",children:[r.jsx("p",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wider mb-3",children:"Signal Breakdown (Kalkulasi Otomatis Sistem)"}),r.jsx(yh,{signals:s.signals,predictive:s.predictive})]}),r.jsxs("div",{className:"border-t border-border px-5 py-4",children:[r.jsx("p",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wider mb-3",children:"Exchange Data"}),r.jsx(_h,{exchangeData:s.exchange_data})]})]}),l&&r.jsxs("div",{className:"border-t border-purple-500/30 bg-bg-card/95 p-4 rounded-b-xl space-y-3 animate-fade-in",children:[r.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-border/60",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"p-1 rounded bg-purple-500/20 text-purple-400",children:r.jsx(Be,{size:14})}),r.jsxs("span",{className:"text-xs font-bold text-purple-300",children:["Hasil Analisa Murni AI (",s.symbol,")"]})]}),r.jsx("span",{className:"text-[10px] text-text-muted italic",children:"*Terpisah dari kalkulasi otomatis sistem"})]}),r.jsx(y.Suspense,{fallback:r.jsxs("div",{className:"py-6 flex items-center justify-center gap-2 text-xs text-text-muted",children:[r.jsx(Pe,{size:14,className:"animate-spin text-purple-400"}),r.jsx("span",{children:"Memuat modul AI..."})]}),children:r.jsx(Eh,{symbol:s.symbol})})]})]})}const Lh=y.memo(Ph,(s,e)=>s.signal.symbol===e.signal.symbol&&s.signal.updated_at===e.signal.updated_at&&s.signal.conviction===e.signal.conviction&&s.signal.direction===e.signal.direction&&s.signal.score===e.signal.score&&s.signal.sniper_grade===e.signal.sniper_grade&&s.signal.veto_reason===e.signal.veto_reason&&s.signal.liquidity_guard?.status===e.signal.liquidity_guard?.status&&s.signal.horizons?.intraday?.score===e.signal.horizons?.intraday?.score&&s.signal.horizons?.intraday?.direction===e.signal.horizons?.intraday?.direction&&s.signal.horizons?.swing?.score===e.signal.horizons?.swing?.score&&s.signal.horizons?.swing?.direction===e.signal.horizons?.swing?.direction&&s.signal.quick_verdict===e.signal.quick_verdict&&s.signal.action===e.signal.action&&s.signal.has_spot===e.signal.has_spot&&s.signal.predictive?.orderbook_skew?.bid_depth_usd===e.signal.predictive?.orderbook_skew?.bid_depth_usd&&s.signal.predictive?.orderbook_skew?.ask_depth_usd===e.signal.predictive?.orderbook_skew?.ask_depth_usd&&s.signal.whale_flow?.flow_verdict===e.signal.whale_flow?.flow_verdict&&s.signal.whale_flow?.twap_bias===e.signal.whale_flow?.twap_bias&&s.signal.whale_flow?.absorption_type===e.signal.whale_flow?.absorption_type&&s.onNavigateToAI===e.onNavigateToAI&&s.onNavigateToChart===e.onNavigateToChart);function Ah({topSignal:s}){const[e,t]=y.useState(!1),[i,n]=y.useState(null),{toast:a}=bt();if(y.useEffect(()=>{let h=!0;const u=()=>{oi.getAccuracy(30).then(x=>{h&&n(x)}).catch(()=>{})};u();const m=setInterval(u,6e4);return()=>{h=!1,clearInterval(m)}},[]),!s||s.direction==="NEUTRAL"||s.conviction<3)return r.jsx("div",{className:"mb-6 p-4 rounded-xl border border-border bg-card/60 backdrop-blur flex items-center justify-between gap-4",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-10 h-10 rounded-xl bg-bg-elevated border border-border flex items-center justify-center shrink-0 text-text-muted",children:r.jsx($o,{size:20})}),r.jsxs("div",{children:[r.jsxs("h3",{className:"text-sm font-semibold text-text-primary flex items-center gap-2",children:["Capital Preservation Mode",r.jsx("span",{className:"text-[10px] font-mono px-2 py-0.5 rounded-full bg-bg-elevated text-text-muted border border-border",children:"No Trades ≥ 3/10"})]}),r.jsx("p",{className:"text-xs text-text-secondary mt-0.5",children:s?.anticipation||"Pasar sedang konsolidasi / chop. Sistem melindungi saldo Anda dari jebakan whipsaw. Tunggu hingga muncul peluang akumulasi institusi."})]})]})});const o=s.direction==="LONG",l=s.trade_levels,c=l?.squeeze_intensity==="EXTREME SQUEEZE"||l?.squeeze_intensity==="MODERATE SQUEEZE",d=()=>{const h=`⚡ PERPS AI FORWARD TRADE SETUP +Pair: ${s.symbol} +Direction: ${s.direction} (Conviction ${s.conviction}/10) +Action: ${s.action||(o?"BUY":"SELL")} +${l?`Entry Zone: ${l.entry_zone} +Stop Loss: ${l.stop_loss_str} +Take Profit 1: ${l.take_profit_1_str} +Take Profit 2: ${l.take_profit_2_str} +🎯 Magnet Target: ${l.predicted_target||"N/A"} (${l.target_type||"Liquidity Pool"}) +R:R: ${l.risk_reward}`:""} +Verdict: ${s.quick_verdict||""} +Forward Anticipation: ${s.anticipation||l?.anticipation||""}`;navigator.clipboard.writeText(h),t(!0),a("Forward trade setup copied to clipboard!","success"),setTimeout(()=>t(!1),2500)};return r.jsx("div",{className:`mb-5 sm:mb-6 p-3.5 sm:p-5 rounded-2xl border transition-all duration-300 relative overflow-hidden ${o?"bg-gradient-to-r from-signal-long/10 via-card to-card border-signal-long/30 shadow-[0_0_25px_rgba(16,185,129,0.12)]":"bg-gradient-to-r from-signal-short/10 via-card to-card border-signal-short/30 shadow-[0_0_25px_rgba(239,68,68,0.12)]"}`,children:r.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-4",children:[r.jsxs("div",{className:"space-y-2 max-w-xl",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsxs("span",{className:`px-2.5 py-1 rounded-lg text-xs font-bold uppercase tracking-wider flex items-center gap-1.5 ${o?"bg-signal-long text-bg-primary font-mono":"bg-signal-short text-white font-mono"}`,children:[r.jsx(ts,{size:13,className:"animate-bounce"}),"TOP SETUP: ",s.symbol]}),r.jsx("span",{className:`font-mono text-xs font-bold px-2 py-0.5 rounded-md border ${o?"bg-signal-long/20 text-signal-long border-signal-long/40":"bg-signal-short/20 text-signal-short border-signal-short/40"}`,children:s.direction}),r.jsxs("span",{className:"font-mono text-xs font-bold text-text-primary px-2 py-0.5 rounded-md bg-bg-elevated border border-border",children:[s.conviction,"/10"]}),s.sniper_grade==="SNIPER_A_PLUS"&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 flex items-center gap-1",children:[r.jsx(Xe,{size:11,className:"text-emerald-400"}),"SNIPER A+"]}),i&&i.total_evaluated>0&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-bold bg-cyan-500/15 text-cyan-300 border border-cyan-500/35 flex items-center gap-1",title:`30d Forward Accuracy (${i.total_evaluated} evaluated | TP Hit Rate: ${i.tp_hit_rate_pct}% | Avg R: ${i.avg_r_multiple>=0?"+":""}${i.avg_r_multiple}R)`,children:["🎯 30d Win Rate:"," ",i.sniper_a_plus.total>0?`${i.sniper_a_plus.win_rate_pct}% (Sniper A+)`:`${i.win_rate_pct}% (${i.total_evaluated})`]}),s.streak&&s.streak>=2&&r.jsxs("span",{className:"font-mono text-xs font-bold px-2 py-0.5 rounded-md bg-amber-500/20 text-amber-300 border border-amber-500/40 flex items-center gap-1 animate-pulse",title:`Consistent Conviction Streak: ${s.streak} cycles`,children:["🔥 ",s.streak,"x Streak"]}),r.jsx("span",{className:"text-[11px] font-mono text-text-secondary uppercase px-1.5 py-0.5 rounded bg-bg-elevated border border-border",children:s.active_timeframe}),s.has_spot===!0&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-medium bg-emerald-500/15 text-emerald-400 border border-emerald-500/30 flex items-center gap-1",children:[r.jsx(Tt,{size:11,className:"text-emerald-400"}),"Spot OK"]}),s.has_spot===!1&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/40 flex items-center gap-1",children:[r.jsx(ve,{size:11,className:"text-amber-400"}),"Perp Only"]}),c&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-bold bg-amber-500/20 text-amber-400 border border-amber-500/30 flex items-center gap-1 animate-pulse",children:[r.jsx(Oe,{size:11}),"Squeeze"]})]}),r.jsx("p",{className:"text-xs sm:text-sm font-medium text-text-primary leading-snug",children:s.quick_verdict||(o?"Peluang akumulasi beli dengan momentum tinggi.":"Peluang tekanan jual agresif terkonfirmasi.")}),s.anticipation&&r.jsxs("div",{className:"flex items-start gap-1.5 text-xs text-accent-blue bg-accent-blue/10 border border-accent-blue/20 px-2.5 py-1.5 rounded-lg",children:[r.jsx("span",{className:"font-semibold shrink-0 text-[11px] font-mono",children:"🔮 Antisipasi:"}),r.jsx("span",{className:"text-text-primary text-[11px] leading-relaxed",children:s.anticipation})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 text-xs text-text-muted pt-0.5",children:[r.jsxs("span",{className:"flex items-center gap-1 text-[11px]",children:[r.jsx(Tt,{size:12,className:"text-accent-blue"}),"Consensus Validated"]}),l?.predicted_target&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"hidden sm:inline text-border",children:"•"}),r.jsxs("span",{className:"flex items-center gap-1 text-text-primary font-mono text-[11px]",children:[r.jsx(Xe,{size:12,className:"text-amber-400"}),"Target Magnet: ",r.jsx("span",{className:"text-amber-300 font-bold",children:l.predicted_target})]})]}),s.has_spot===!1&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"hidden sm:inline text-border",children:"•"}),r.jsxs("span",{className:"flex items-center gap-1 text-amber-400 text-[11px] font-medium",children:[r.jsx(ve,{size:12}),"Perp-Only (Disiplin Stop Loss!)"]})]})]})]}),l?r.jsx("div",{className:"bg-bg-primary/90 border border-border/80 p-3 sm:p-3.5 rounded-xl backdrop-blur shrink-0",children:r.jsxs("div",{className:"grid grid-cols-2 sm:flex sm:items-center gap-2 sm:gap-3",children:[r.jsxs("div",{className:"space-y-0.5 pr-2 sm:border-r sm:border-border col-span-2 sm:col-span-1 bg-bg-elevated/40 sm:bg-transparent p-2 sm:p-0 rounded-lg",children:[r.jsx("p",{className:"text-[9px] uppercase tracking-wider text-text-muted font-medium",children:"Entry Zone"}),r.jsx("p",{className:"font-mono text-xs font-bold text-text-primary",children:l.entry_zone})]}),r.jsxs("div",{className:"space-y-0.5 px-0 sm:px-2 sm:border-r sm:border-border bg-bg-elevated/40 sm:bg-transparent p-2 sm:p-0 rounded-lg",children:[r.jsx("p",{className:"text-[9px] uppercase tracking-wider text-signal-short font-medium",children:"Stop Loss"}),r.jsx("p",{className:"font-mono text-xs font-bold text-signal-short",children:l.stop_loss_str})]}),r.jsxs("div",{className:"space-y-0.5 px-0 sm:px-2 sm:border-r sm:border-border bg-bg-elevated/40 sm:bg-transparent p-2 sm:p-0 rounded-lg",children:[r.jsx("p",{className:"text-[9px] uppercase tracking-wider text-signal-long font-medium",children:"TP1 / TP2"}),r.jsxs("p",{className:"font-mono text-xs font-bold text-signal-long",children:[l.take_profit_1_str," / ",l.take_profit_2_str]})]}),l.predicted_target&&r.jsxs("div",{className:"space-y-0.5 px-0 sm:px-2 sm:border-r sm:border-border bg-bg-elevated/40 sm:bg-transparent p-2 sm:p-0 rounded-lg col-span-2 sm:col-span-1",children:[r.jsx("p",{className:"text-[9px] uppercase tracking-wider text-amber-400 font-medium",children:"Magnet Target"}),r.jsx("p",{className:"font-mono text-xs font-bold text-amber-300",children:l.predicted_target})]}),r.jsxs("button",{onClick:d,className:"col-span-2 sm:col-span-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg bg-bg-elevated hover:bg-border border border-border text-xs font-semibold text-text-primary transition-all active:scale-95",title:"Copy Trade Signal to Clipboard",children:[e?r.jsx(at,{size:14,className:"text-signal-long"}):r.jsx(es,{size:14}),r.jsx("span",{children:e?"Copied!":"Copy Plan"})]})]})}):r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("button",{onClick:d,className:"w-full sm:w-auto flex items-center justify-center gap-1.5 px-3.5 py-2 rounded-lg bg-bg-elevated hover:bg-border border border-border text-xs font-semibold text-text-primary transition-all",children:[e?r.jsx(at,{size:14,className:"text-signal-long"}):r.jsx(es,{size:14}),r.jsx("span",{children:e?"Copied":"Copy Signal"})]})})]})})}const Oh=y.memo(Ah,(s,e)=>s.topSignal?.symbol===e.topSignal?.symbol&&s.topSignal?.updated_at===e.topSignal?.updated_at&&s.topSignal?.conviction===e.topSignal?.conviction&&s.topSignal?.direction===e.topSignal?.direction&&s.topSignal?.sniper_grade===e.topSignal?.sniper_grade&&s.topSignal?.veto_reason===e.topSignal?.veto_reason&&s.topSignal?.quick_verdict===e.topSignal?.quick_verdict&&s.topSignal?.has_spot===e.topSignal?.has_spot&&s.topSignal?.anticipation===e.topSignal?.anticipation),zh=y.lazy(()=>xt(()=>import("./AddPairModal-DCQtFcNW.js"),__vite__mapDeps([0,1,2,3])).then(s=>({default:s.AddPairModal})));function Ih({onNavigateToAI:s,onNavigateToChart:e,isMobileDrawerOpen:t,setIsMobileDrawerOpen:i}){const[n,a]=y.useState(null),[o,l]=y.useState("ALL"),[c,d]=y.useState("STABLE"),[h,u]=y.useState(!1),{data:m=[],isLoading:x,error:b}=us(),{data:f=[],isLoading:g}=li(),{mutate:p,isPending:v}=Ga(),{mutate:S,isPending:j}=Ch(),k=b?.status,C=k===401||k===503,E=y.useMemo(()=>{const A=new Set(m.filter(_=>_.is_active).map(_=>_.symbol));return[...f.filter(_=>A.has(_.symbol))].sort((_,B)=>B.conviction!==_.conviction?B.conviction-_.conviction:_.symbol.localeCompare(B.symbol))},[f,m]),T=y.useMemo(()=>E.find(A=>A.direction!=="NEUTRAL"&&A.conviction>=3),[E]),D=y.useMemo(()=>{if(n)return f.filter(H=>H.symbol===n);const A=E.filter(H=>o==="SPOT_ONLY"?H.has_spot===!0:o==="PERP_ONLY"?H.has_spot===!1:o==="HOT"?H.conviction>=4:o==="LONG"?H.direction==="LONG":o==="SHORT"?H.direction==="SHORT":!0);return c==="STABLE"?[...A].sort((H,_)=>H.symbol.localeCompare(_.symbol)):A},[n,E,o,c,f]);y.useEffect(()=>{if(n&&!v){const A=f.find(_=>_.symbol===n);(!A||!A.updated_at||Date.now()-new Date(A.updated_at).getTime()>18e4)&&p(n)}},[n,f,v,p]),y.useEffect(()=>{if(f.length===0||j)return;const A=()=>{const _=Date.now();f.filter(Y=>{const F=Y.updated_at?new Date(Y.updated_at).getTime():0;return!F||_-F>18e4}).length>5&&!j&&S()};A();const H=setInterval(A,6e4);return()=>clearInterval(H)},[f,j,S]);const O=m.filter(A=>A.is_active),M=(x||g)&&m.length===0&&f.length===0,R=!M&&O.length===0,L=n!==null&&D.length===0,$=!M&&!n&&O.length>0&&E.length===0,z=y.useMemo(()=>E.filter(A=>A.has_spot===!0).length,[E]),V=y.useMemo(()=>E.filter(A=>A.has_spot===!1).length,[E]),q=y.useMemo(()=>E.filter(A=>A.conviction>=4).length,[E]),Z=y.useMemo(()=>E.filter(A=>A.direction==="LONG").length,[E]),ae=y.useMemo(()=>E.filter(A=>A.direction==="SHORT").length,[E]);return r.jsxs("div",{className:"flex flex-1 h-full overflow-hidden bg-bg-primary",children:[r.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[r.jsx("div",{className:"hidden md:flex",children:r.jsx(hh,{pairs:m,signals:f,isLoading:x,selectedSymbol:n,onSelect:A=>a(H=>H===A?null:A)})}),r.jsx(uh,{isOpen:t,onClose:()=>i(!1),pairs:m,signals:f,isLoading:x,selectedSymbol:n,onSelect:A=>a(A),onOpenAddModal:()=>u(!0)}),r.jsxs("main",{className:"flex-1 overflow-y-auto p-3 sm:p-5 custom-scrollbar pb-20 md:pb-5",children:[C&&r.jsxs("div",{className:"mb-4 p-3.5 rounded-xl bg-amber-500/10 border border-amber-500/35 text-xs text-amber-200 flex items-start gap-2.5",children:[r.jsx(ve,{size:16,className:"text-amber-400 shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("p",{className:"font-semibold",children:k===503?"Backend Memerlukan PERPS_API_TOKEN":"API Bearer Token Belum Terpasang / Tidak Cocok"}),r.jsx("p",{className:"text-[11px] text-amber-200/80 mt-0.5",children:b?.message||"Klik indikator status koneksi di pojok kanan atas Header untuk mengisi PERPS_API_TOKEN agar Watchlist Pair & Jurnal aktif."})]})]}),!n&&E.length>0&&r.jsx(Oh,{topSignal:T}),n&&r.jsxs("div",{className:"mb-4 flex items-center justify-between gap-2 p-2.5 sm:p-3 rounded-xl bg-accent-blue/10 border border-accent-blue/30 text-xs animate-fade-in",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"font-mono font-bold text-text-primary text-sm sm:text-base truncate",children:n}),r.jsx("span",{className:"text-[10px] sm:text-[11px] text-accent-blue font-semibold uppercase px-1.5 py-0.5 rounded bg-accent-blue/15 border border-accent-blue/30 shrink-0",children:"Fokus Pair"})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>p(n),loading:v,icon:r.jsx(Pe,{size:12,className:v?"animate-spin":""}),className:"text-xs h-8 px-2 sm:px-3",children:r.jsx("span",{className:"hidden xs:inline",children:"Refresh"})}),r.jsx(se,{variant:"primary",size:"sm",onClick:()=>a(null),icon:r.jsx(Do,{size:13}),className:"text-xs h-8 px-2.5 sm:px-3.5 shadow-sm",children:"Semua Pair"})]})]}),!n&&r.jsxs("div",{className:"flex flex-col gap-3 mb-4 sm:mb-5",children:[r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-base sm:text-lg font-bold text-text-primary leading-tight",children:"Market Conviction Overview"}),r.jsxs("p",{className:"text-[11px] sm:text-xs text-text-secondary mt-0.5",children:["Menampilkan ",D.length," dari ",E.length," pair aktif"]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 shrink-0",children:[r.jsxs("button",{type:"button",onClick:()=>S(),disabled:j,className:"px-2.5 py-1.5 rounded-lg text-xs font-medium border border-border bg-bg-elevated hover:bg-bg-card text-text-secondary hover:text-text-primary flex items-center gap-1.5 transition-all shadow-sm shrink-0 active:scale-95 disabled:opacity-60",title:"Perbarui seluruh data sinyal pasar sekarang",children:[r.jsx(Pe,{size:12,className:j?"animate-spin text-accent-blue":""}),r.jsx("span",{className:"hidden xs:inline",children:j?"Memperbarui...":"Refresh Pasar"})]}),r.jsxs("button",{type:"button",onClick:()=>d(A=>A==="STABLE"?"CONVICTION":"STABLE"),className:"px-2.5 py-1.5 rounded-lg text-xs font-medium border border-border bg-bg-elevated hover:bg-bg-card text-text-secondary hover:text-text-primary flex items-center gap-1.5 transition-all shadow-sm shrink-0",title:c==="STABLE"?"Posisi kartu stabil (A-Z, kartu tidak loncat-loncat)":"Diurutkan berdasarkan skor keyakinan tertinggi",children:[r.jsx("span",{className:"text-[10px] text-text-muted hidden xs:inline",children:"Tata Letak:"}),r.jsx("span",{className:"font-semibold text-text-primary",children:c==="STABLE"?"📌 A-Z":"🔥 Skor"})]})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 p-1 rounded-xl bg-bg-elevated/70 border border-border/80 overflow-x-auto no-scrollbar",children:[r.jsxs("button",{onClick:()=>l("ALL"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all shrink-0 ${o==="ALL"?"bg-card text-text-primary shadow-sm font-semibold":"text-text-secondary hover:text-text-primary"}`,children:[r.jsx(Xs,{size:13}),r.jsxs("span",{children:["All (",E.length,")"]})]}),r.jsxs("button",{onClick:()=>l("SPOT_ONLY"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all shrink-0 ${o==="SPOT_ONLY"?"bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 font-semibold":"text-text-secondary hover:text-emerald-400"}`,title:"Hanya pair yang memiliki pasar Spot riil (Aman dari manipulasi bandar perp-only)",children:[r.jsx(Tt,{size:13,className:"text-emerald-400"}),r.jsxs("span",{children:["🛡️ Aman (",z,")"]})]}),r.jsxs("button",{onClick:()=>l("PERP_ONLY"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all shrink-0 ${o==="PERP_ONLY"?"bg-amber-500/20 text-amber-300 border border-amber-500/40 font-semibold":"text-text-secondary hover:text-amber-400"}`,title:"Hanya pair PERP-ONLY tanpa pasar Spot (Rawan manipulasi bandar)",children:[r.jsx(ve,{size:13,className:"text-amber-400"}),r.jsxs("span",{children:["⚠️ Rawan (",V,")"]})]}),r.jsxs("button",{onClick:()=>l("HOT"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all shrink-0 ${o==="HOT"?"bg-amber-500/20 text-amber-400 border border-amber-500/30 font-semibold":"text-text-secondary hover:text-amber-400"}`,children:[r.jsx(ts,{size:13,className:q>0?"text-amber-400":""}),r.jsxs("span",{children:["Ready ≥4 (",q,")"]})]}),r.jsxs("button",{onClick:()=>l("LONG"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all shrink-0 ${o==="LONG"?"bg-signal-long/20 text-signal-long border border-signal-long/30 font-semibold":"text-text-secondary hover:text-signal-long"}`,children:[r.jsx(aa,{size:13}),r.jsxs("span",{children:["Longs (",Z,")"]})]}),r.jsxs("button",{onClick:()=>l("SHORT"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all shrink-0 ${o==="SHORT"?"bg-signal-short/20 text-signal-short border border-signal-short/30 font-semibold":"text-text-secondary hover:text-signal-short"}`,children:[r.jsx(oa,{size:13}),r.jsxs("span",{children:["Shorts (",ae,")"]})]})]})]}),M&&r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3 sm:gap-4",children:[...Array(3)].map((A,H)=>r.jsx(nh,{},H))}),R&&r.jsxs("div",{className:"flex flex-col items-center justify-center h-[55vh] text-center space-y-4 p-4",children:[r.jsx("div",{className:"w-14 h-14 rounded-2xl bg-accent-blue/10 border border-accent-blue/20 flex items-center justify-center",children:r.jsx(Je,{size:26,className:"text-accent-blue"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Belum Ada Trading Pair"}),r.jsx("p",{className:"text-xs text-text-secondary mt-1 max-w-xs",children:"Tambahkan trading pair pertama Anda untuk mulai menganalisa sinyal perpetual futures."})]}),r.jsx(se,{variant:"primary",size:"md",onClick:()=>u(!0),icon:r.jsx(lr,{size:15}),children:"Tambah Pair Pertama"})]}),L&&r.jsxs("div",{className:"flex flex-col items-center justify-center h-[45vh] text-center space-y-4 animate-fade-in p-4",children:[r.jsx("div",{className:"w-14 h-14 rounded-2xl bg-accent-blue/10 border border-accent-blue/20 flex items-center justify-center",children:r.jsx(nn,{size:"md"})}),r.jsxs("div",{children:[r.jsxs("h3",{className:"text-sm font-semibold text-text-primary",children:["Menganalisa ",n,"..."]}),r.jsx("p",{className:"text-xs text-text-secondary mt-1 max-w-xs",children:"Mengalkulasi CVD, Open Interest, Funding Rate, dan Market Structure dari Binance, Bybit, OKX, dan Hyperliquid."})]})]}),$&&r.jsxs("div",{className:"flex flex-col items-center justify-center h-[40vh] text-center space-y-4 p-4",children:[r.jsx("div",{className:"w-12 h-12 rounded-2xl bg-bg-elevated border border-border flex items-center justify-center",children:r.jsx(nn,{size:"md"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Memuat Sinyal Pasar"}),r.jsx("p",{className:"text-xs text-text-secondary mt-1 max-w-xs",children:"Mengambil data live bursa dan konsensus multi-exchange..."})]})]}),!M&&D.length===0&&E.length>0&&!n&&r.jsxs("div",{className:"flex flex-col items-center justify-center h-[35vh] text-center space-y-3 p-5 sm:p-6 rounded-2xl border border-border bg-card",children:[r.jsx("div",{className:"w-12 h-12 rounded-xl bg-bg-elevated border border-border flex items-center justify-center text-text-muted",children:r.jsx(ts,{size:20})}),r.jsxs("h3",{className:"text-sm font-semibold text-text-primary",children:['Tidak Ada Pair yang Memenuhi Filter "',o,'"']}),r.jsx("p",{className:"text-xs text-text-secondary max-w-md",children:o==="HOT"?"Saat ini belum ada coin dengan conviction ≥ 4/10. Jangan fomo atau paksakan entry. Bersantai dulu sampai setup institusi yang valid muncul!":`Tidak ada sinyal aktif dengan arah ${o}.`}),r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>l("ALL"),children:"Reset ke Semua Pair"})]}),!M&&D.length>0&&r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3 sm:gap-4",children:D.map(A=>r.jsx(Lh,{signal:A,onNavigateToAI:s,onNavigateToChart:e},A.symbol))})]})]}),h&&r.jsx(y.Suspense,{fallback:null,children:r.jsx(zh,{isOpen:h,onClose:()=>u(!1)})})]})}const $h=[{id:"anthropic/claude-fable-5",label:"Claude Fable 5 (Vikey Default)",category:"Anthropic"},{id:"anthropic/claude-fable-5.1",label:"Claude Fable 5.1",category:"Anthropic"},{id:"anthropic/claude-sonnet-5.5",label:"Claude Sonnet 5.5",category:"Anthropic"},{id:"anthropic/claude-sonnet-5",label:"Claude Sonnet 5",category:"Anthropic"},{id:"anthropic/claude-opus-5.5",label:"Claude Opus 5.5",category:"Anthropic"},{id:"anthropic/haiku-5.5",label:"Claude Haiku 5.5 (Fast)",category:"Anthropic"},{id:"deepseek/deepseek-v4-pro",label:"DeepSeek V4 Pro",category:"DeepSeek"},{id:"deepseek/deepseek-v4-flash",label:"DeepSeek V4 Flash",category:"DeepSeek"},{id:"deepseek/deepseek-v4.1-flash",label:"DeepSeek V4.1 Flash",category:"DeepSeek"},{id:"openai/gpt-5.6-sol",label:"GPT-5.6 Sol",category:"OpenAI"},{id:"openai/gpt-6-astra",label:"GPT-6 Astra",category:"OpenAI"},{id:"openai/gpt-5.6-luna",label:"GPT-5.6 Luna",category:"OpenAI"},{id:"openai/gpt-6.1-sol",label:"GPT-6.1 Sol",category:"OpenAI"},{id:"gemini/gemini-3.8-flash",label:"Gemini 3.8 Flash",category:"Google"},{id:"gemini/gemini-3.7-flash-high",label:"Gemini 3.7 Flash High",category:"Google"},{id:"qwen/qwen3.8-max",label:"Qwen 3.8 Max",category:"Qwen"},{id:"vikey/qwen3.8-27b-uncensored",label:"Qwen 3.8 27B Uncensored",category:"Qwen"},{id:"moonshot/kimi-k3",label:"Moonshot Kimi K3",category:"Moonshot"},{id:"minimax/minimax-m3",label:"MiniMax M3",category:"MiniMax"},{id:"zai/glm-5.3",label:"ZAI GLM 5.3",category:"GLM"}],Dh=[{id:"gemini-2.5-flash",label:"Gemini 2.5 Flash (Recommended)"},{id:"gemini-1.5-flash",label:"Gemini 1.5 Flash"},{id:"gemini-2.0-flash",label:"Gemini 2.0 Flash"},{id:"gemini-1.5-pro",label:"Gemini 1.5 Pro"}],Bh=[{id:"gpt-4o-mini",label:"GPT-4o Mini (Fast)"},{id:"gpt-4o",label:"GPT-4o"},{id:"o3-mini",label:"o3-mini"}],Fh=[{id:"openai/gpt-4o-mini",label:"GPT-4o Mini (Recommended)"},{id:"anthropic/claude-3.5-sonnet",label:"Claude 3.5 Sonnet"},{id:"deepseek/deepseek-chat",label:"DeepSeek V3 Chat"},{id:"openai/gpt-4o",label:"GPT-4o"}],Uh=[{id:"llama-3.3-70b-versatile",label:"Llama 3.3 70B Versatile (Recommended)"},{id:"deepseek-r1-distill-llama-70b",label:"DeepSeek R1 Distill Llama 70B"},{id:"llama-3.1-8b-instant",label:"Llama 3.1 8B Instant (Fast)"}],Ci="perps_ai_settings_changed";function Ei(){const s=localStorage.getItem("perps_ai_provider")||"vikey",e=localStorage.getItem("perps_ai_api_key")||"";let t=localStorage.getItem("perps_ai_model")||"";t||(s==="vikey"?t="anthropic/claude-fable-5":s==="gemini"?t="gemini-2.5-flash":s==="openrouter"?t="openai/gpt-4o-mini":s==="groq"?t="llama-3.3-70b-versatile":t="gpt-4o-mini");const i=localStorage.getItem("perps_ai_base_url")||"",n=localStorage.getItem("perps_ai_max_tokens"),a=n?parseInt(n,10):void 0;return{provider:s,api_key:e,model:t,base_url:i,max_tokens:a}}function ci(){const[s,e]=y.useState(Ei),t=y.useCallback(()=>{e(Ei())},[]);y.useEffect(()=>(window.addEventListener(Ci,t),window.addEventListener("storage",t),()=>{window.removeEventListener(Ci,t),window.removeEventListener("storage",t)}),[t]);const i=a=>{const l={...Ei(),...a};if(a.provider!==void 0&&localStorage.setItem("perps_ai_provider",l.provider),a.api_key!==void 0&&localStorage.setItem("perps_ai_api_key",l.api_key.trim()),a.model!==void 0&&localStorage.setItem("perps_ai_model",l.model.trim()),"base_url"in a){const c=l.base_url?.trim()||"";c?localStorage.setItem("perps_ai_base_url",c):localStorage.removeItem("perps_ai_base_url")}a.max_tokens!==void 0&&(a.max_tokens?localStorage.setItem("perps_ai_max_tokens",String(a.max_tokens)):localStorage.removeItem("perps_ai_max_tokens")),e(l),window.dispatchEvent(new Event(Ci))},n=!!(s.api_key&&s.api_key.trim());return{settings:s,isConfigured:n,updateSettings:i,reloadSettings:t}}const qh={analyze:async s=>{const{data:e}=await ie.post("/api/ai/analyze",s,{timeout:0});return e}},Ae={logTrade:async s=>{const{data:e}=await ie.post("/api/journal/log",s);return e},getEntries:async(s="ALL",e=50,t=0)=>{const{data:i}=await ie.get("/api/journal",{params:{status:s,limit:e,offset:t}});return i},updateStatus:async(s,e,t,i,n,a)=>{const{data:o}=await ie.patch(`/api/journal/${s}/status`,{status:e,note:t,failure_tag:i,exit_price:n,holding_duration_seconds:a});return o},deleteEntry:async s=>{const{data:e}=await ie.delete(`/api/journal/${s}`);return e},getStats:async()=>{const{data:s}=await ie.get("/api/journal/stats");return s},getMemory:async()=>{const{data:s}=await ie.get("/api/journal/memory");return s},synthesizeAudit:async s=>{const{data:e}=await ie.post("/api/journal/audit",s);return e}};function Wh(...s){return ps(ms(s))}const Hh={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl"};function Is({isOpen:s,onClose:e,title:t,children:i,size:n="md"}){const a=y.useCallback(o=>{o.key==="Escape"&&e()},[e]);return y.useEffect(()=>(s&&(document.addEventListener("keydown",a),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",a),document.body.style.overflow=""}),[s,a]),s?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4",children:[r.jsx("div",{className:"absolute inset-0 bg-black/80 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:Wh("relative w-full max-h-[92vh] flex flex-col card shadow-2xl animate-fade-in my-auto",Hh[n]),onClick:o=>o.stopPropagation(),children:[r.jsxs("div",{className:"shrink-0 flex items-center justify-between px-4 sm:px-6 py-3.5 sm:py-4 border-b border-border",children:[r.jsx("h2",{className:"text-sm sm:text-base font-semibold text-text-primary truncate",children:t}),r.jsx("button",{onClick:e,className:"p-1.5 rounded-lg text-text-secondary hover:text-text-primary hover:bg-bg-elevated transition-colors ml-2 shrink-0",children:r.jsx(Et,{size:16})})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-4 sm:px-6 py-4 sm:py-5 custom-scrollbar",children:i})]})]}):null}const yr="perps_bybit_session_creds";function Vs(){if(typeof window>"u")return null;try{const s=window.sessionStorage.getItem(yr);if(!s)return null;const e=JSON.parse(s);if(e?.api_key&&e?.api_secret)return{api_key:String(e.api_key).trim(),api_secret:String(e.api_secret).trim(),mode:e.mode||"demo"}}catch{}return null}function Vh(s){typeof window>"u"||window.sessionStorage.setItem(yr,JSON.stringify({api_key:s.api_key.trim(),api_secret:s.api_secret.trim(),mode:s.mode}))}function Kh(){typeof window>"u"||window.sessionStorage.removeItem(yr)}function ys(s){const e=Vs();return e?{"X-Bybit-Api-Key":e.api_key,"X-Bybit-Api-Secret":e.api_secret,"X-Bybit-Mode":s||e.mode}:s?{"X-Bybit-Mode":s}:{}}const ws={getSettings:async()=>{const{data:s}=await ie.get("/api/execution/bybit/settings",{headers:ys()});return s},saveSettings:async s=>{const e=s.mode||"demo",{data:t}=await ie.post("/api/execution/bybit/settings",s,{headers:ys(e)});return t.success&&s.api_key&&s.api_secret&&Vh({api_key:s.api_key,api_secret:s.api_secret,mode:e}),t},getBalance:async s=>{const{data:e}=await ie.get("/api/execution/bybit/balance",{params:s?{mode:s}:{},headers:ys(s)});return e},executeOrder:async s=>{const e=Vs(),t={...s,api_key:s.api_key||e?.api_key,api_secret:s.api_secret||e?.api_secret,mode:s.mode||e?.mode},{data:i}=await ie.post("/api/execution/bybit/order",t,{headers:ys(t.mode)});return i}};function Ve(s){if(!s)return null;const e=s.match(/\$\s*([0-9]+(?:,[0-9]{3})*(?:\.[0-9]+)?|[0-9]+(?:\.[0-9]+)?)/);if(e&&e[1]){const n=parseFloat(e[1].replace(/,/g,""));if(!isNaN(n)&&n>0)return n}const i=s.replace(/\b(TP[12]|1[Hh]|4[Hh]|15[Mm]|5[Mm]|24[Hh]|1[Dd])\b[:\s-]*/gi,"").match(/([0-9]+(?:,[0-9]{3})*(?:\.[0-9]+)?|[0-9]+(?:\.[0-9]+)?)/);if(i&&i[1]){const n=parseFloat(i[1].replace(/,/g,""));if(!isNaN(n)&&n>0)return n}return null}function on(s){if(!s)return 3;const e=s.match(/([0-9]+)\s*x/i);if(e&&e[1]){const t=parseInt(e[1],10);if(!isNaN(t)&&t>0)return Math.min(Math.max(t,1),50)}return 3}function Qa({isOpen:s,onClose:e,symbol:t,summary:i,markPrice:n,onExecutionSuccess:a}){const{toast:o}=bt(),l=i.bias.toUpperCase().includes("SHORT")||i.bias.toUpperCase().includes("SELL"),c=l?"Sell":"Buy",d=Ve(i.entryZone)||n||0,h=Ve(i.stopLoss)||(l?d*1.03:d*.97),u=Ve(i.takeProfit1)||(l?d*.95:d*1.05),m=Ve(i.takeProfit2),x=on(i.leverage),[b,f]=y.useState("Limit"),[g,p]=y.useState("percent"),[v,S]=y.useState(5),[j,k]=y.useState(50),[C,E]=y.useState(x),[T,D]=y.useState(d),[O,M]=y.useState(h),[R,L]=y.useState(u),[$,z]=y.useState(m),[V,q]=y.useState(50),[Z,ae]=y.useState(!0),[A,H]=y.useState(null),[_,B]=y.useState(null),[Y,F]=y.useState(!1),[le,K]=y.useState(""),[te,be]=y.useState(""),[Se,tt]=y.useState("demo"),[ge,we]=y.useState(!1),[N,Q]=y.useState(!1),[J,ee]=y.useState(null),W=y.useRef(null);y.useEffect(()=>{if(!s){W.current=null;return}const U=`${t}:${l?"SHORT":"LONG"}`;if(W.current===U)return;const Te=Ve(i.entryZone)||n||0;Te>0&&(W.current=U);const Eo=Ve(i.stopLoss)||(l?Te*1.03:Te*.97),To=Ve(i.takeProfit1)||(l?Te*.95:Te*1.05),Ro=Ve(i.takeProfit2),Po=on(i.leverage);D(Te),M(Eo),L(To),z(Ro),E(Po)},[s,t,l,i.entryZone,i.stopLoss,i.takeProfit1,i.takeProfit2,i.leverage,n]),y.useEffect(()=>{if(s){const U=Vs();U&&tt(U.mode),X()}},[s]);const X=async()=>{ee(null);try{const U=await ws.getSettings();H(U),tt(U.mode||"demo"),U.configured?(F(!1),ze(U.mode)):F(!0)}catch(U){const Te=U?.status;Te===401||Te===503?(ee(U?.message||"API Bearer Token belum diset / tidak cocok. Buka ikon status server di header untuk mengisi PERPS_API_TOKEN."),F(!1)):F(!0)}},ke=()=>{Kh(),K(""),be(""),B(null),o("Kredensial Bybit sesi browser telah dihapus dari memori lokal.","success"),X()},ze=async U=>{try{const Te=await ws.getBalance(U);B(Te)}catch{}},xs=async()=>{if(!le.trim()||!te.trim()){o("Masukkan API Key dan API Secret Bybit Anda.","error");return}we(!0);try{const U=await ws.saveSettings({api_key:le.trim(),api_secret:te.trim(),mode:Se});o(U.message,"success"),H({configured:!0,masked_key:`${le.slice(0,4)}***`,mode:Se}),U.balance&&B(U.balance),F(!1)}catch(U){o(U.message||"Kredensial Bybit gagal divalidasi.","error")}finally{we(!1)}},Ee=_?.total_equity&&_.total_equity>0?_.total_equity:_?.available_balance&&_.available_balance>0?_.available_balance:0,qe=Ee>0?Math.max(1,Math.round(Ee*(v/100)*100)/100):0,bi=g==="percent"&&Ee>0?qe:j,oe=b==="Limit"&&T>0?T:n||T||1,bs=bi*C,gi=oe>0?(l?(O-oe)/oe:(oe-O)/oe)*bs:0,vi=!!($&&$>0&&V<100),jo=vi?V/100:1,_o=vi?(100-V)/100:0,So=oe>0&&R>0?(l?(oe-R)/oe:(R-oe)/oe)*(bs*jo):0,ko=oe>0&&vi&&$?(l?(oe-$)/oe:($-oe)/oe)*(bs*_o):0,Rr=So+ko,Mo=gi>0?(Rr/gi).toFixed(2):"N/A",Co=async()=>{if(!A?.configured){F(!0),o("Harap masukkan API Key Bybit sebelum eksekusi.","info");return}if(g==="percent"){if(Ee<=0){o('Total equity Bybit terdeteksi $0 atau API belum terhubung. Silakan beralih ke tab "$ USD Tetap" atau hubungkan API Bybit.',"error");return}if(v<=0||v>100){o("Persentase alokasi equity harus antara 0.1% hingga 100%.","error");return}}else if(j<=0){o("Masukkan margin yang valid (> $0).","error");return}if(bi<=0){o("Margin efektif tidak valid atau $0.","error");return}if(b==="Limit"&&T<=0){o("Harga Entry Limit wajib lebih besar dari $0.","error");return}if(O<=0||R<=0){o("Stop Loss dan Target TP1 wajib diisi.","error");return}if(c==="Buy"){if(O>=oe){o(`Stop Loss ($${O}) harus lebih rendah dari Entry ($${oe}) untuk posisi Long.`,"error");return}if(R<=oe){o(`Target TP1 ($${R}) harus lebih tinggi dari Entry ($${oe}) untuk posisi Long.`,"error");return}if($&&V<100&&$<=R){o(`Target TP2 ($${$}) harus lebih tinggi dari TP1 ($${R}).`,"error");return}}else{if(O<=oe){o(`Stop Loss ($${O}) harus lebih tinggi dari Entry ($${oe}) untuk posisi Short.`,"error");return}if(R>=oe){o(`Target TP1 ($${R}) harus lebih rendah dari Entry ($${oe}) untuk posisi Short.`,"error");return}if($&&V<100&&$>=R){o(`Target TP2 ($${$}) harus lebih rendah dari TP1 ($${R}).`,"error");return}}Q(!0);try{const U=await ws.executeOrder({symbol:t,side:c,order_type:b,margin_usd:bi,margin_percent:g==="percent"?v:null,leverage:C,stop_loss:O,take_profit_1:R,take_profit_2:V<100?$:null,tp1_percent:V,auto_breakeven:V<100&&$?Z:!1,entry_price:b==="Limit"?T:void 0,mark_price:n,summary_tldr:i.verdictSummary});o(`🚀 ${U.message}`,"success"),a&&a(U),e()}catch(U){o(U.message||"Eksekusi order gagal.","error")}finally{Q(!1)}};return r.jsx(Is,{isOpen:s,onClose:e,title:`Eksekusi Order — ${t}`,size:"lg",children:r.jsxs("div",{className:"space-y-4 text-xs",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 p-3 rounded-xl bg-bg-elevated/60 border border-border",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:`px-2.5 py-1 rounded-lg text-xs font-bold font-mono flex items-center gap-1.5 border ${l?"bg-rose-500/20 text-rose-300 border-rose-500/40":"bg-emerald-500/20 text-emerald-300 border-emerald-500/40"}`,children:[l?r.jsx(Ct,{size:14}):r.jsx(Je,{size:14}),r.jsxs("span",{children:[c.toUpperCase()," (",i.bias,")"]})]}),r.jsxs("span",{className:"text-[11px] text-text-muted font-mono hidden sm:inline",children:["Mark: ",n!=null&&n>0?n>=1e3?`$${n.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`:n>=1?`$${n.toFixed(4)}`:n>=.01?`$${n.toFixed(6)}`:`$${n.toFixed(8)}`:"N/A"]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[A?.configured?r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-emerald-500/10 border border-emerald-500/30 text-[11px] text-emerald-300 font-mono",children:[r.jsx(ra,{size:12,className:"text-emerald-400"}),r.jsxs("span",{className:"font-semibold uppercase",children:[A.mode," Bybit"]}),_&&r.jsxs("span",{className:"text-emerald-400 font-bold ml-1",children:["$",(_.total_equity||_.available_balance).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})," USDT"]})]}):r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-amber-500/15 border border-amber-500/30 text-[11px] text-amber-300 font-mono",children:[r.jsx(ve,{size:12,className:"text-amber-400"}),r.jsx("span",{children:"API Belum Terpasang"})]}),r.jsx("button",{type:"button",onClick:()=>F(!Y),className:"p-1.5 rounded-lg bg-bg-card hover:bg-bg-elevated border border-border text-text-muted hover:text-text-primary transition-colors",title:"Konfigurasi API Key Bybit",children:r.jsx(Bo,{size:13})})]})]}),J&&r.jsxs("div",{className:"p-3 rounded-xl bg-rose-500/15 border border-rose-500/40 text-rose-200 flex items-start gap-2.5 text-xs",children:[r.jsx(ve,{size:15,className:"text-rose-400 shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("p",{className:"font-semibold",children:"Autentikasi Server Dibutuhkan"}),r.jsx("p",{className:"text-[11px] text-rose-200/80 mt-0.5",children:J})]})]}),Y&&r.jsxs("div",{className:"p-3.5 rounded-xl bg-purple-950/30 border border-purple-500/40 space-y-3 animate-fade-in",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[r.jsxs("span",{className:"text-xs font-bold text-purple-200 flex items-center gap-1.5",children:[r.jsx(Fo,{size:14,className:"text-purple-400"}),"Kredensial API Bybit (Stateless Per-Sesi)"]}),r.jsxs("span",{className:"text-[10px] text-purple-300/80 flex items-center gap-1",children:[r.jsx(Uo,{size:10})," Disimpan hanya di sessionStorage & dikirim per-request"]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2.5",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-[10px] uppercase font-bold text-text-muted block mb-1",children:"Bybit API Key"}),r.jsx("input",{type:"text",value:le,onChange:U=>K(U.target.value),placeholder:"Masukkan API Key Bybit",className:"w-full px-2.5 py-1.5 rounded-lg bg-bg-card border border-border text-xs text-text-primary font-mono focus:border-purple-500 focus:outline-none"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-[10px] uppercase font-bold text-text-muted block mb-1",children:"Bybit API Secret"}),r.jsx("input",{type:"password",value:te,onChange:U=>be(U.target.value),placeholder:"Masukkan API Secret Bybit",className:"w-full px-2.5 py-1.5 rounded-lg bg-bg-card border border-border text-xs text-text-primary font-mono focus:border-purple-500 focus:outline-none"})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-[10px] font-bold text-text-muted uppercase",children:"Lingkungan:"}),r.jsx("div",{className:"flex items-center gap-1",children:[{id:"demo",label:"Bybit Demo (api-demo)"},{id:"testnet",label:"Testnet"},{id:"real",label:"Live Real"}].map(U=>r.jsx("button",{type:"button",onClick:()=>tt(U.id),className:`px-2 py-1 rounded text-[10px] font-mono font-semibold transition-all ${Se===U.id?"bg-purple-600 text-white shadow-sm":"bg-bg-card text-text-secondary hover:text-text-primary border border-border"}`,children:U.label},U.id))})]}),r.jsxs("div",{className:"flex items-center gap-1.5",children:[Vs()&&r.jsx(se,{variant:"ghost",size:"sm",onClick:ke,icon:r.jsx(Qt,{size:12}),className:"text-rose-300 hover:text-rose-200",children:"Hapus Key Sesi"}),A?.configured&&r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>F(!1),children:"Batal"}),r.jsx(se,{variant:"primary",size:"sm",onClick:xs,loading:ge,className:"bg-purple-600 hover:bg-purple-500 text-white",children:"Simpan & Hubungkan"})]})]})]}),r.jsxs("div",{className:"p-3.5 rounded-xl bg-bg-elevated/40 border border-border space-y-3",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:"text-[11px] font-bold uppercase tracking-wider text-text-secondary flex items-center gap-1.5",children:[r.jsx(qo,{size:13,className:"text-purple-400"}),"Alokasi Modal Margin"]}),r.jsxs("div",{className:"flex items-center rounded-lg border border-border bg-bg-card p-0.5",children:[r.jsx("button",{type:"button",onClick:()=>p("percent"),className:`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${g==="percent"?"bg-purple-600 text-white shadow-sm":"text-text-muted hover:text-text-primary"}`,children:"% Equity"}),r.jsx("button",{type:"button",onClick:()=>p("usd"),className:`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${g==="usd"?"bg-purple-600 text-white shadow-sm":"text-text-muted hover:text-text-primary"}`,children:"$ USD"})]})]}),r.jsxs("span",{className:"text-[11px] font-mono font-bold text-purple-300",children:["Notional Posisi: $",bs.toLocaleString(void 0,{minimumFractionDigits:1,maximumFractionDigits:1})," USD"]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsx("div",{className:"space-y-1.5",children:g==="percent"?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",min:"0.5",max:"100",step:"0.5",value:v,onChange:U=>S(Math.max(.1,parseFloat(U.target.value)||0)),className:"w-full pl-3 pr-8 py-1.5 rounded-lg bg-bg-card border border-border text-sm font-bold font-mono text-text-primary focus:border-purple-500 focus:outline-none"}),r.jsx("span",{className:"absolute right-3 top-2 text-text-muted font-mono text-xs font-bold",children:"%"})]}),r.jsx("div",{className:"flex items-center gap-1",children:[1,2,5,10,20].map(U=>r.jsxs("button",{type:"button",onClick:()=>S(U),className:`px-2 py-1.5 rounded-lg text-[10px] font-mono font-semibold border transition-all ${v===U?"bg-purple-600/30 border-purple-500 text-purple-200":"bg-bg-card border-border text-text-muted hover:text-text-primary"}`,children:[U,"%"]},U))})]}),r.jsx("div",{className:"text-[10.5px] font-mono",children:Ee>0?r.jsxs("span",{className:"text-purple-300",children:["⚡ ",r.jsxs("strong",{children:[v,"%"]})," = ",r.jsxs("strong",{className:"text-emerald-400",children:["$",qe.toFixed(2)," USD"]})," (dari equity $",Ee.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2}),")"]}):r.jsxs("span",{className:"text-amber-400/90 flex items-center gap-1",children:[r.jsx(ve,{size:11}),' Saldo equity $0 / belum terhubung. Silakan gunakan tab "$ USD".']})})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-2 text-text-muted font-mono text-xs",children:"$"}),r.jsx("input",{type:"number",min:"5",max:"50000",step:"5",value:j,onChange:U=>k(Math.max(1,parseFloat(U.target.value)||0)),className:"w-full pl-7 pr-3 py-1.5 rounded-lg bg-bg-card border border-border text-sm font-bold font-mono text-text-primary focus:border-purple-500 focus:outline-none"})]}),r.jsx("div",{className:"flex items-center gap-1",children:[25,50,100,200].map(U=>r.jsxs("button",{type:"button",onClick:()=>k(U),className:`px-2 py-1.5 rounded-lg text-[10px] font-mono font-semibold border transition-all ${j===U?"bg-purple-600/30 border-purple-500 text-purple-200":"bg-bg-card border-border text-text-muted hover:text-text-primary"}`,children:["$",U]},U))})]}),r.jsx("div",{className:"text-[10.5px] font-mono text-text-muted",children:Ee>0?r.jsxs("span",{children:["ℹ️ $",j.toFixed(2)," USD ≈ ",r.jsxs("strong",{className:"text-purple-300",children:[(j/Ee*100).toFixed(1),"%"]})," dari total equity ($",Ee.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2}),")"]}):r.jsxs("span",{children:["ℹ️ Nominal margin tetap $",j.toFixed(2)," USD"]})})]})}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex-1",children:[r.jsxs("div",{className:"flex items-center justify-between text-[10px] text-text-muted mb-1",children:[r.jsx("span",{className:"uppercase font-bold",children:"Leverage:"}),r.jsxs("span",{className:"font-mono text-purple-300 font-bold",children:[C,"x"]})]}),r.jsx("input",{type:"range",min:"1",max:"25",step:"1",value:C,onChange:U=>E(parseInt(U.target.value,10)),className:"w-full accent-purple-500 cursor-pointer"})]}),r.jsxs("div",{className:"flex items-center rounded-lg border border-border bg-bg-card p-0.5 shrink-0 self-end",children:[r.jsx("button",{type:"button",onClick:()=>f("Limit"),className:`px-2.5 py-1.5 rounded-md text-[10px] font-bold transition-all ${b==="Limit"?"bg-purple-600 text-white shadow-sm":"text-text-muted"}`,children:"Limit"}),r.jsx("button",{type:"button",onClick:()=>f("Market"),className:`px-2.5 py-1.5 rounded-md text-[10px] font-bold transition-all ${b==="Market"?"bg-purple-600 text-white shadow-sm":"text-text-muted"}`,children:"Market"})]})]})]})]}),r.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[r.jsxs("div",{className:"p-2.5 rounded-xl bg-bg-card border border-border space-y-1",children:[r.jsx("span",{className:"text-[9px] uppercase font-bold text-text-muted block",children:b==="Limit"?"ENTRY PRICE (LIMIT)":"ENTRY MARKET"}),r.jsx("input",{type:"number",step:"any",disabled:b==="Market",value:T,onChange:U=>D(parseFloat(U.target.value)||0),className:"w-full px-2 py-1 rounded bg-bg-elevated border border-border text-xs font-mono font-bold text-text-primary focus:border-purple-500 focus:outline-none disabled:opacity-50"})]}),r.jsxs("div",{className:"p-2.5 rounded-xl bg-rose-500/10 border border-rose-500/25 space-y-1",children:[r.jsxs("span",{className:"text-[9px] uppercase font-bold text-rose-300/80 flex items-center justify-between",children:[r.jsx("span",{children:"STOP LOSS (SL)"}),r.jsx(Rt,{size:11,className:"text-rose-400"})]}),r.jsx("input",{type:"number",step:"any",value:O,onChange:U=>M(parseFloat(U.target.value)||0),className:"w-full px-2 py-1 rounded bg-bg-elevated border border-rose-500/40 text-xs font-mono font-bold text-rose-400 focus:border-rose-400 focus:outline-none"})]}),r.jsxs("div",{className:"p-2.5 rounded-xl bg-emerald-500/10 border border-emerald-500/25 space-y-1",children:[r.jsxs("span",{className:"text-[9px] uppercase font-bold text-emerald-300/80 flex items-center justify-between",children:[r.jsx("span",{children:"TARGET TP1"}),r.jsx(Xe,{size:11,className:"text-emerald-400"})]}),r.jsx("input",{type:"number",step:"any",value:R,onChange:U=>L(parseFloat(U.target.value)||0),className:"w-full px-2 py-1 rounded bg-bg-elevated border border-emerald-500/40 text-xs font-mono font-bold text-emerald-400 focus:border-emerald-400 focus:outline-none"})]}),r.jsxs("div",{className:"p-2.5 rounded-xl bg-emerald-500/10 border border-emerald-500/25 space-y-1",children:[r.jsxs("span",{className:"text-[9px] uppercase font-bold text-emerald-300/80 flex items-center justify-between",children:[r.jsx("span",{children:"TARGET TP2"}),r.jsx(Xe,{size:11,className:"text-emerald-400"})]}),r.jsx("input",{type:"number",step:"any",value:$||"",onChange:U=>z(U.target.value?parseFloat(U.target.value):null),placeholder:"Opsional",className:"w-full px-2 py-1 rounded bg-bg-elevated border border-emerald-500/40 text-xs font-mono font-bold text-emerald-300 focus:border-emerald-400 focus:outline-none"})]})]}),r.jsxs("div",{className:"p-3.5 rounded-xl bg-purple-950/20 border border-purple-500/30 space-y-2.5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("span",{className:"text-[11px] font-bold uppercase tracking-wider text-purple-200 flex items-center gap-1.5",children:[r.jsx(Oe,{size:13,className:"text-purple-400"}),"Porsi Ambil Cuan TP1 (Custom Split)"]}),r.jsx("div",{className:"flex items-center gap-1",children:[25,50,75,100].map(U=>r.jsxs("button",{type:"button",onClick:()=>q(U),className:`px-2 py-0.5 rounded text-[10px] font-mono font-bold transition-all ${V===U?"bg-purple-600 text-white shadow-sm":"bg-bg-card border border-border text-text-muted hover:text-text-primary"}`,children:[U,"%"]},U))})]}),r.jsxs("div",{className:"space-y-1",children:[r.jsx("input",{type:"range",min:"10",max:"100",step:"5",value:V,onChange:U=>q(parseInt(U.target.value,10)),className:"w-full accent-purple-500 cursor-pointer"}),r.jsxs("div",{className:"flex items-center justify-between text-[10px] font-mono text-purple-300/90",children:[r.jsxs("span",{children:["TP1: ",V,"%"]}),r.jsx("span",{children:V<100?`TP2: ${100-V}%`:"TP2: Dinonaktifkan"})]})]}),r.jsx("p",{className:"text-[11px] text-purple-200/90 leading-tight",children:V>=100?r.jsxs("span",{children:["🎯 100% posisi akan ditutup penuh di ",r.jsx("strong",{children:"TP1"})," saat harga tercapai."]}):r.jsxs("span",{children:["🎯 ",r.jsxs("strong",{children:[V,"%"]})," posisi akan ditutup di ",r.jsx("strong",{children:"TP1"})," ($",R,"), dan sisa ",r.jsxs("strong",{children:[100-V,"%"]})," dibiarkan berlari ke ",r.jsx("strong",{children:"TP2"})," ($",$||"Runner",")."]})}),V<100&&!!$&&r.jsx("div",{className:"pt-2 border-t border-purple-500/20 flex items-start justify-between gap-3",children:r.jsxs("label",{className:"flex items-start gap-2 cursor-pointer select-none",children:[r.jsx("input",{type:"checkbox",checked:Z,onChange:U=>ae(U.target.checked),className:"mt-0.5 accent-emerald-500 rounded cursor-pointer"}),r.jsxs("div",{className:"space-y-0.5",children:[r.jsx("span",{className:"text-[11px] font-bold text-emerald-300 block",children:"🛡️ Auto-Breakeven SL setelah TP1 (+6 bps Fee Buffer)"}),r.jsx("span",{className:"text-[10px] text-text-muted block leading-snug",children:"Saat TP1 tercapai, SL sisa runner otomatis digeser ke Harga Entry ±6 bps (aktif 12 jam di server persistent; manual di mode serverless)."})]})]})})]}),r.jsxs("div",{className:"p-3 rounded-xl bg-bg-elevated/40 border border-border flex flex-wrap items-center justify-between gap-3 text-xs",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-[10px] text-text-muted uppercase font-bold block",children:"POTENSI CUAN TOTAL"}),r.jsxs("span",{className:"text-sm font-bold font-mono text-emerald-400",children:["+$",Rr.toFixed(2)," USD"]})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-[10px] text-text-muted uppercase font-bold block",children:"MAKSIMAL RISIKO (SL)"}),r.jsxs("span",{className:"text-sm font-bold font-mono text-rose-400",children:["-$",Math.abs(gi).toFixed(2)," USD"]})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-[10px] text-text-muted uppercase font-bold block",children:"RISK / REWARD RIIL"}),r.jsxs("span",{className:"text-sm font-bold font-mono text-purple-300",children:["1 : ",Mo]})]})]}),r.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2 border-t border-border/50",children:[r.jsx(se,{variant:"ghost",size:"md",onClick:e,disabled:N,children:"Batal"}),r.jsx(se,{variant:"primary",size:"md",onClick:Co,loading:N,icon:r.jsx(Oe,{size:15}),className:"bg-purple-600 hover:bg-purple-500 text-white font-bold px-5 shadow-lg shadow-purple-600/30",children:"Eksekusi Order ke Bybit"})]})]})})}function Gh(s){return s?s.replace(/\*\*/g,"").replace(/^[•\s:–—-]+|[•\s:–—-]+$/g,"").trim():""}function Ne(s,e){for(const t of e){const i=s.match(t);if(i&&i[1]){const n=Gh(i[1]);if(n)return n}}return""}function Qh(s,e,t,i){if(!s||typeof s!="string")return null;const n=/Zona Entry|Entry Zone|Actionable Trade Setup|Rencana Trading|Dynamic Stop Loss/i.test(s),a=/EXECUTIVE VERDICT|Executive Summary|Ringkasan Eksekutif|Directional Bias/i.test(s);if(!n&&!a)return null;let o=Ne(s,[/(?:Directional\s+)?Bias[:\s*]+([^\n\r]+)/i,/EXECUTIVE VERDICT.*?Bias[:\s*]+([^\n\r]+)/is]);!o&&e&&(o=e);let l=Ne(s,[/Ringkasan Eksekutif(?:\s*\([^)]*\))?[:\s*]+([^\n\r]+)/i,/Executive Summary(?:\s*\([^)]*\))?[:\s*]+([^\n\r]+)/i,/Sintesis Padat[:\s*]+([^\n\r]+)/i]),c=Ne(s,[/Zona Entry(?:\s*\([^)]*\))?[:\s*]+([^\n\r]+)/i,/Entry Zone[:\s*]+([^\n\r]+)/i,/Entry Price[:\s*]+([^\n\r]+)/i]);!c&&i?.entry_zone&&(c=i.entry_zone);let d=Ne(s,[/(?:Dynamic\s+)?Stop Loss(?:\s*\(SL\))?[:\s*]+([^\n\r]+)/i,/\bSL[:\s*]+([^\n\r]+)/i]);!d&&i?.stop_loss_str&&(d=i.stop_loss_str);let h=Ne(s,[/Take Profit(?:\s*\([^)]*\))?[:\s*]+([^\n\r]+)/i,/\bTP[:\s*]+([^\n\r]+)/i]),u="",m="";if(h){const C=h.match(/TP1[^:]*:\s*(\$?[0-9,.]+)/i),E=h.match(/TP2[^:]*:\s*(\$?[0-9,.]+)/i);C&&(u=C[1]),E&&(m=E[1])}!u&&i?.take_profit_1_str&&(u=i.take_profit_1_str),!m&&i?.take_profit_2_str&&(m=i.take_profit_2_str);let x=Ne(s,[/Risk[\s/]*Reward[:\s*]+([^\n\r]+)/i,/\bRR[:\s*]+([^\n\r]+)/i]);!x&&i?.risk_reward&&(x=i.risk_reward);let b=Ne(s,[/Rekomendasi Leverage(?: & Sizing)?[:\s*]+([^\n\r]+)/i,/Leverage(?: & Sizing)?[:\s*]+([^\n\r]+)/i,/Leverage[:\s*]+([^\n\r]+)/i]),f=Ne(s,[/Kondisi Invalidasi(?: Kritis)?[:\s*]+([^\n\r]+)/i,/Invalidasi(?: Kritis)?[:\s*]+([^\n\r]+)/i]),g=Ne(s,[/Target Sapuan Likuidasi(?:\s*\([^)]*\))?[:\s*]+([^\n\r]+)/i,/Magnet Likuidasi[:\s*]+([^\n\r]+)/i,/Liquidation Magnet[:\s*]+([^\n\r]+)/i]);!g&&(t?.upper_magnet||t?.lower_magnet)&&(g=[t.upper_magnet,t.lower_magnet].filter(Boolean).join(" / "));let p=Ne(s,[/Spot CVD vs Futures CVD(?:\s*&[^\n:]*)?[:\s*]+([^\n\r]+)/i,/Status Aliran CVD[:\s*]+([^\n\r]+)/i]);!p&&t?.cvd_verdict&&(p=t.cvd_verdict);let v=Ne(s,[/Confluence Consensus[:\s*]+([^\n\r]+)/i,/Konsensus Sinyal[:\s*]+([^\n\r]+)/i]),S=Ne(s,[/Disparitas Harga & Bursa Pendorong(?:\s*\(Lead-Lag\))?[:\s*]+([^\n\r]+)/i,/Disparitas Harga[:\s*]+([^\n\r]+)/i,/Lead-Lag[:\s*]+([^\n\r]+)/i]);!S&&t?.lead_lag_spread_bps!=null&&Number.isFinite(t.lead_lag_spread_bps)&&(S=`${t.lead_lag_spread_bps.toFixed(1)} bps (${t.leading_exchange?.toUpperCase()||"BALANCED"})`);let j=Ne(s,[/Funding Rate,\s*(?:Countdown\s+)?Settlement(?: & Carry)?(?:\s*\(APR\))?[:\s*]+([^\n\r]+)/i,/Jadwal Settlement Terdekat[:\s*]+([^\n\r]+)/i,/Countdown Settlement[:\s*]+([^\n\r]+)/i]);!j&&t?.funding_countdown&&(j=t.funding_countdown);let k=Ne(s,[/Radar Squeeze & Breakout[:\s*]+([^\n\r]+)/i,/Energi Volatilitas & Profil 24 Jam[:\s*]+([^\n\r]+)/i,/Squeeze Radar[:\s*]+([^\n\r]+)/i]);return!k&&t?.breakout_radar?.is_breakout_primed&&(k=`${t.breakout_radar.radar_label} (${t.breakout_radar.squeeze_stage})`),o||c||d||l?{bias:o||"ANALYZED",verdictSummary:l||"Analisa kuantitatif selesai dihitung.",entryZone:c||"Sesuai level S/R terdekat",stopLoss:d||"Lihat SL di narasi analisa",takeProfit1:u,takeProfit2:m,takeProfitRaw:h||(u?`TP1: ${u} | TP2: ${m}`:"Lihat TP di analisa"),riskReward:x||"1 : 1.5+",leverage:b||"2x - 3x aman",invalidation:f||"Penutupan candle 1H berlawanan arah bias",liquidationMagnet:g,flowStatus:p,confluenceConsensus:v,leadLag:S,fundingSettlement:j,breakoutRadar:k}:null}function Yh(s){const e=(s||"").toUpperCase();return e.includes("STRONG LONG")||e.includes("STRONG BUY")?{theme:"long",badgeBg:"bg-emerald-500/20 text-emerald-300 border-emerald-500/40",borderGlow:"border-emerald-500/40 hover:border-emerald-500/60 shadow-emerald-950/30",gradientBg:"from-emerald-950/25 via-bg-elevated/40 to-bg-card",icon:Je,accentText:"text-emerald-400",glowDot:"bg-emerald-400 shadow-emerald-400/50"}:e.includes("LONG")||e.includes("BUY")?{theme:"long",badgeBg:"bg-cyan-500/20 text-cyan-300 border-cyan-500/40",borderGlow:"border-cyan-500/40 hover:border-cyan-500/60 shadow-cyan-950/30",gradientBg:"from-cyan-950/20 via-bg-elevated/40 to-bg-card",icon:Je,accentText:"text-cyan-400",glowDot:"bg-cyan-400 shadow-cyan-400/50"}:e.includes("STRONG SHORT")||e.includes("STRONG SELL")?{theme:"short",badgeBg:"bg-rose-500/20 text-rose-300 border-rose-500/40",borderGlow:"border-rose-500/40 hover:border-rose-500/60 shadow-rose-950/30",gradientBg:"from-rose-950/25 via-bg-elevated/40 to-bg-card",icon:Ct,accentText:"text-rose-400",glowDot:"bg-rose-400 shadow-rose-400/50"}:e.includes("SHORT")||e.includes("SELL")?{theme:"short",badgeBg:"bg-rose-500/20 text-rose-300 border-rose-500/40",borderGlow:"border-rose-500/40 hover:border-rose-500/60 shadow-rose-950/30",gradientBg:"from-rose-950/20 via-bg-elevated/40 to-bg-card",icon:Ct,accentText:"text-rose-400",glowDot:"bg-rose-400 shadow-rose-400/50"}:{theme:"neutral",badgeBg:"bg-amber-500/20 text-amber-300 border-amber-500/40",borderGlow:"border-amber-500/30 hover:border-amber-500/50 shadow-amber-950/30",gradientBg:"from-amber-950/20 via-bg-elevated/40 to-bg-card",icon:Rt,accentText:"text-amber-400",glowDot:"bg-amber-400 shadow-amber-400/50"}}function Jh({symbol:s,content:e,bias:t,dataSnapshot:i,tradeLevels:n,modelUsed:a}){const[o,l]=y.useState(!1),[c,d]=y.useState(!1),[h,u]=y.useState(!1),[m,x]=y.useState(!1),{toast:b}=bt();y.useEffect(()=>{u(!1),l(!1)},[s,e]);const f=Qh(e,t,i,n);if(!f)return null;const g=Yh(f.bias),p=g.icon,v=f.takeProfit1?f.takeProfit2?`TP1: ${f.takeProfit1} | TP2: ${f.takeProfit2}`:`TP1: ${f.takeProfit1}`:f.takeProfitRaw,S=()=>{const k=`⚡ [${s}] DAMIAN TRADE VERDICT: ${f.bias} +📍 Entry: ${f.entryZone} +🛑 Stop Loss: ${f.stopLoss} +🎯 Target TP: ${v} +⚖️ Risk/Reward: ${f.riskReward} +⚡ Leverage: ${f.leverage} +⚠️ Invalidasi: ${f.invalidation}`;navigator.clipboard.writeText(k),l(!0),b("Setup trading disalin ke clipboard!","success"),setTimeout(()=>l(!1),2e3)},j=async()=>{if(!(c||h)){d(!0);try{const k=await Ae.logTrade({symbol:s,bias:f.bias,entry_zone:f.entryZone,stop_loss:f.stopLoss,take_profit:v,risk_reward:f.riskReward,leverage:f.leverage,invalidation:f.invalidation,summary_tldr:f.verdictSummary,full_analysis:e,model_used:a,snapshot_data:i});u(!0),k?.entry&&window.dispatchEvent(new CustomEvent("journal-updated",{detail:k.entry})),b(`[${s}] Setup trading berhasil dicatat ke Jurnal!`,"success")}catch(k){b(k.message||"Gagal menyimpan ke Jurnal","error")}finally{d(!1)}}};return r.jsxs("div",{className:`rounded-2xl border bg-gradient-to-b ${g.gradientBg} ${g.borderGlow} p-4 sm:p-5 space-y-4 shadow-md transition-all animate-fade-in relative overflow-hidden`,children:[r.jsx("div",{className:"absolute top-0 left-0 right-0 h-[2px] bg-gradient-to-r from-transparent via-purple-500 to-transparent opacity-70"}),r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2.5 pb-3 border-b border-border/50",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("div",{className:"p-1.5 rounded-lg bg-purple-500/20 text-purple-300 flex items-center justify-center",children:r.jsx(Wo,{size:15})}),r.jsxs("div",{children:[r.jsx("span",{className:"text-[10px] uppercase font-bold tracking-wider text-purple-300 block",children:"Kesimpulan Eksekutif Damian"}),r.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[r.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-mono font-bold border ${g.badgeBg}`,children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full shadow-sm animate-pulse ${g.glowDot}`}),r.jsx(p,{size:12}),r.jsx("span",{children:f.bias})]}),r.jsx("span",{className:"text-[11px] font-mono text-text-muted font-bold",children:s})]})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[r.jsxs("button",{type:"button",onClick:()=>x(!0),className:"px-3 py-1.5 rounded-lg border border-purple-500/50 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white text-[11px] font-bold flex items-center gap-1.5 transition-all shadow-md shadow-purple-600/25 active:scale-95 group",title:"Eksekusi setup ini secara presisi ke bursa",children:[r.jsx(Oe,{size:12,className:"text-yellow-300 fill-yellow-300 group-hover:scale-110 transition-transform"}),r.jsx("span",{children:"Eksekusi Order"})]}),r.jsx("button",{type:"button",onClick:j,disabled:c||h,className:`px-2.5 py-1.5 rounded-lg border text-[11px] font-medium flex items-center gap-1.5 transition-all shadow-sm ${h?"bg-emerald-500/15 border-emerald-500/40 text-emerald-300 cursor-default":"border-purple-500/40 bg-purple-600/20 hover:bg-purple-600/30 text-purple-200"}`,title:"Catat trade ini ke Jurnal untuk ditrack hasilnya",children:h?r.jsxs(r.Fragment,{children:[r.jsx(at,{size:12,className:"text-emerald-400"}),r.jsx("span",{className:"font-semibold text-emerald-300",children:"Tercatat di Jurnal"})]}):r.jsxs(r.Fragment,{children:[r.jsx(Ho,{size:12,className:"text-purple-300"}),r.jsx("span",{children:"📌 Catat ke Jurnal"})]})}),r.jsx("button",{type:"button",onClick:S,className:"px-2.5 py-1.5 rounded-lg border border-border/80 bg-bg-card hover:bg-bg-elevated text-[11px] font-medium text-text-secondary hover:text-purple-300 flex items-center gap-1.5 transition-all shadow-sm group",title:"Salin setup order trading ke clipboard",children:o?r.jsxs(r.Fragment,{children:[r.jsx(at,{size:12,className:"text-emerald-400"}),r.jsx("span",{className:"text-emerald-400 font-semibold",children:"Tersalin!"})]}):r.jsxs(r.Fragment,{children:[r.jsx(es,{size:12,className:"text-text-muted group-hover:text-purple-400 transition-colors"}),r.jsx("span",{children:"Salin Order"})]})})]})]}),f.verdictSummary&&r.jsxs("div",{className:"p-3 rounded-xl bg-purple-500/10 border border-purple-500/20 text-xs text-text-primary leading-relaxed flex items-start gap-2.5",children:[r.jsx(Fe,{size:15,className:"text-purple-400 shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("span",{className:"font-semibold text-purple-200 block text-[11px] mb-0.5",children:"💡 Intisari Pasar (TL;DR):"}),r.jsx("span",{className:"text-text-primary",children:f.verdictSummary})]})]}),r.jsxs("div",{className:"grid grid-cols-1 xs:grid-cols-2 lg:grid-cols-4 gap-2.5",children:[r.jsxs("div",{className:"p-3 rounded-xl bg-bg-elevated/70 border border-border/80 flex flex-col justify-between space-y-1",children:[r.jsxs("div",{className:"flex items-center justify-between text-text-muted",children:[r.jsx("span",{className:"text-[9px] uppercase font-bold tracking-wider",children:"ZONA ENTRY"}),r.jsx(cr,{size:12,className:"text-purple-400"})]}),r.jsx("div",{className:"text-xs sm:text-sm font-bold font-mono text-text-primary break-words",children:f.entryZone}),r.jsx("span",{className:"text-[9px] text-text-muted",children:"Area konfirmasi pullback S/R"})]}),r.jsxs("div",{className:"p-3 rounded-xl bg-rose-500/10 border border-rose-500/25 flex flex-col justify-between space-y-1",children:[r.jsxs("div",{className:"flex items-center justify-between text-rose-300/80",children:[r.jsx("span",{className:"text-[9px] uppercase font-bold tracking-wider",children:"STOP LOSS (SL)"}),r.jsx(Rt,{size:12,className:"text-rose-400"})]}),r.jsx("div",{className:"text-xs sm:text-sm font-bold font-mono text-rose-400 break-words",children:f.stopLoss}),r.jsx("span",{className:"text-[9px] text-rose-300/70",children:"Di luar zona wick hunt"})]}),r.jsxs("div",{className:"p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/25 flex flex-col justify-between space-y-1",children:[r.jsxs("div",{className:"flex items-center justify-between text-emerald-300/80",children:[r.jsx("span",{className:"text-[9px] uppercase font-bold tracking-wider",children:"TARGET CUAN (TP)"}),r.jsx(Xe,{size:12,className:"text-emerald-400"})]}),r.jsx("div",{className:"text-xs sm:text-sm font-bold font-mono text-emerald-400 break-words",children:f.takeProfit1?r.jsxs("div",{className:"space-y-0.5",children:[r.jsxs("span",{className:"block",children:["TP1: ",f.takeProfit1]}),f.takeProfit2&&r.jsxs("span",{className:"block text-[11px] text-emerald-300/90 font-medium",children:["TP2: ",f.takeProfit2]})]}):f.takeProfitRaw}),r.jsx("span",{className:"text-[9px] text-emerald-300/70",children:"Target magnet likuidasi"})]}),r.jsxs("div",{className:"p-3 rounded-xl bg-purple-500/10 border border-purple-500/25 flex flex-col justify-between space-y-1",children:[r.jsxs("div",{className:"flex items-center justify-between text-purple-300/80",children:[r.jsx("span",{className:"text-[9px] uppercase font-bold tracking-wider",children:"RISK / REWARD & LEV"}),r.jsx(Vo,{size:12,className:"text-purple-400"})]}),r.jsxs("div",{className:"text-xs sm:text-sm font-bold font-mono text-purple-300 break-words",children:["R:R ",f.riskReward]}),r.jsxs("div",{className:"flex items-start gap-1 text-[10px] text-purple-200/80 font-mono",children:[r.jsx(Oe,{size:10,className:"text-purple-400 shrink-0 mt-0.5"}),r.jsx("span",{className:"break-words leading-tight",children:f.leverage})]})]})]}),f.invalidation&&r.jsxs("div",{className:"px-3 py-2 rounded-xl bg-amber-500/10 border border-amber-500/25 text-[11px] text-amber-200 flex items-start gap-2",children:[r.jsx(ve,{size:13,className:"text-amber-400 shrink-0 mt-0.5"}),r.jsxs("div",{className:"leading-tight",children:[r.jsx("span",{className:"font-semibold text-amber-300 mr-1.5",children:"Syarat Batal (Invalidasi):"}),r.jsx("span",{className:"text-amber-100/90",children:f.invalidation})]})]}),(f.liquidationMagnet||f.flowStatus||f.confluenceConsensus||f.leadLag||f.fundingSettlement||f.breakoutRadar)&&r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1 text-[10px] font-mono text-text-muted",children:[f.breakoutRadar&&r.jsxs("div",{className:"px-2 py-0.5 rounded-md bg-purple-500/20 border border-purple-500/40 text-purple-300 flex items-center gap-1 animate-pulse",children:[r.jsx("span",{className:"text-yellow-400",children:"🚨 Squeeze:"}),r.jsx("span",{className:"font-semibold text-purple-200",children:f.breakoutRadar})]}),f.liquidationMagnet&&r.jsxs("div",{className:"px-2 py-0.5 rounded-md bg-bg-card border border-border flex items-center gap-1",children:[r.jsx("span",{className:"text-purple-400",children:"🧲 Magnet:"}),r.jsx("span",{className:"text-text-primary font-medium",children:f.liquidationMagnet})]}),f.flowStatus&&r.jsxs("div",{className:"px-2 py-0.5 rounded-md bg-bg-card border border-border flex items-center gap-1",children:[r.jsx("span",{className:"text-cyan-400",children:"🌊 Flow:"}),r.jsx("span",{className:"text-text-primary font-medium",children:f.flowStatus})]}),f.confluenceConsensus&&r.jsxs("div",{className:"px-2 py-0.5 rounded-md bg-bg-card border border-border flex items-center gap-1",children:[r.jsx("span",{className:"text-emerald-400",children:"🎯 Konsensus:"}),r.jsx("span",{className:"text-text-primary font-medium",children:f.confluenceConsensus})]}),f.leadLag&&r.jsxs("div",{className:"px-2 py-0.5 rounded-md bg-bg-card border border-border flex items-center gap-1",children:[r.jsx("span",{className:"text-cyan-400",children:"⚡ Lead-Lag:"}),r.jsx("span",{className:"text-text-primary font-medium",children:f.leadLag})]}),f.fundingSettlement&&r.jsxs("div",{className:"px-2 py-0.5 rounded-md bg-bg-card border border-border flex items-center gap-1",children:[r.jsx("span",{className:"text-amber-400",children:"⏱️ Settle:"}),r.jsx("span",{className:"text-text-primary font-medium",children:f.fundingSettlement})]})]}),r.jsx(Qa,{isOpen:m,onClose:()=>x(!1),symbol:s,summary:f,markPrice:i?.mark_price,onExecutionSuccess:()=>{u(!0),window.dispatchEvent(new CustomEvent("journal-updated"))}})]})}function Ke(s){if(!s)return null;const e=s.trim(),t=/(\*\*[^*]+?\*\*|`[^`]+`|\*[^*]+?\*|_[^_]+?_)/g;return e.split(t).map((n,a)=>{if(!n)return null;if(n.startsWith("**")&&n.endsWith("**")&&n.length>=4){const l=n.slice(2,-2).trim(),c=l.toUpperCase();return c.includes("BUY ON PULLBACK")||c.includes("STRONG LONG")||c.includes("STRONG BUY")||c==="LONG"||c==="BUY"?r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[11px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 shadow-sm align-middle mx-0.5",children:[r.jsx(Je,{size:11,className:"text-emerald-400"}),r.jsx("span",{children:l})]},a):c.includes("SELL ON RALLY")||c.includes("STRONG SHORT")||c.includes("STRONG SELL")||c==="SHORT"||c==="SELL"?r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[11px] font-mono font-bold bg-rose-500/20 text-rose-300 border border-rose-500/40 shadow-sm align-middle mx-0.5",children:[r.jsx(Ct,{size:11,className:"text-rose-400"}),r.jsx("span",{children:l})]},a):c.includes("WAIT-AND-SEE")||c.includes("WAIT AND SEE")||c.includes("WAIT & SEE")||c==="NEUTRAL"?r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[11px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/40 shadow-sm align-middle mx-0.5",children:[r.jsx(Rt,{size:11,className:"text-amber-400"}),r.jsx("span",{children:l})]},a):r.jsx("strong",{className:"font-bold text-text-primary",children:l},a)}if(n.startsWith("`")&&n.endsWith("`")&&n.length>=2)return r.jsx("code",{className:"font-mono text-[11px] bg-bg-elevated px-1.5 py-0.5 rounded text-amber-300 border border-border/60 mx-0.5 font-semibold",children:n.slice(1,-1)},a);if(n.startsWith("*")&&n.endsWith("*")&&n.length>=2||n.startsWith("_")&&n.endsWith("_")&&n.length>=2)return r.jsx("em",{className:"italic text-text-secondary",children:n.slice(1,-1)},a);const o=n.replace(/\*\*/g,"");return r.jsx("span",{children:o},a)})}function Xh(s){const e=s.toUpperCase();return e.includes("EXECUTIVE")||e.includes("VERDICT")||e.includes("🏛️")?{border:"border-purple-500/30",bg:"bg-purple-950/15",badgeBg:"bg-purple-500/20 text-purple-300 border-purple-500/30",icon:r.jsx(Fe,{size:14,className:"text-purple-400"}),dot:"bg-purple-400"}:e.includes("ANATOMI")||e.includes("MODAL")||e.includes("CVD")||e.includes("🌊")?{border:"border-cyan-500/30",bg:"bg-cyan-950/15",badgeBg:"bg-cyan-500/20 text-cyan-300 border-cyan-500/30",icon:r.jsx(Ko,{size:14,className:"text-cyan-400"}),dot:"bg-cyan-400"}:e.includes("MIKROSTRUKTUR")||e.includes("VOLATILITAS")||e.includes("MAGNET")||e.includes("🧲")?{border:"border-amber-500/30",bg:"bg-amber-950/15",badgeBg:"bg-amber-500/20 text-amber-300 border-amber-500/30",icon:r.jsx(Go,{size:14,className:"text-amber-400"}),dot:"bg-amber-400"}:e.includes("SETUP")||e.includes("ACTIONABLE")||e.includes("TRADE")||e.includes("🎯")?{border:"border-emerald-500/30",bg:"bg-emerald-950/15",badgeBg:"bg-emerald-500/20 text-emerald-300 border-emerald-500/30",icon:r.jsx(cr,{size:14,className:"text-emerald-400"}),dot:"bg-emerald-400"}:e.includes("PENGAMAN")||e.includes("MEMORI")||e.includes("EVALUASI")||e.includes("🛡️")?{border:"border-rose-500/30",bg:"bg-rose-950/15",badgeBg:"bg-rose-500/20 text-rose-300 border-rose-500/30",icon:r.jsx(wt,{size:14,className:"text-rose-400"}),dot:"bg-rose-400"}:{border:"border-border/80",bg:"bg-bg-elevated/40",badgeBg:"bg-bg-elevated text-text-primary border-border",icon:r.jsx(Fe,{size:14,className:"text-purple-400"}),dot:"bg-purple-400"}}function Zh(s){const e=s.trim();return e?!!(e.startsWith("#")||e.startsWith("===")&&e.endsWith("===")||/^(?:[^\w\s]+\s*)?\d+\.\s+[A-Z\s/()&,.-]{4,}/u.test(e)||/^[^\w\s]+\s+[A-Z\s/()&,.-]{5,}/u.test(e)):!1}function Ya({content:s,className:e=""}){if(!s)return null;const t=s.split(/\r?\n/),i=[];let n={id:"intro",title:"",rawHeader:"",items:[]};for(const a of t){const o=a.trim();o&&(Zh(o)?((n.title||n.items.length>0)&&i.push(n),n={id:`sec-${i.length}`,title:o.replace(/^#+\s*/,"").replace(/^===\s*/,"").replace(/\s*===$/,""),rawHeader:o,items:[]}):n.items.push(o))}return(n.title||n.items.length>0)&&i.push(n),i.length===1&&!i[0].title?r.jsx("div",{className:`space-y-2 text-xs sm:text-[13px] text-text-primary leading-relaxed ${e}`,children:i[0].items.map((a,o)=>r.jsx("p",{children:Ke(a)},o))}):r.jsx("div",{className:`space-y-3 font-sans text-xs sm:text-[13px] ${e}`,children:i.map((a,o)=>{const l=Xh(a.title);return r.jsxs("div",{className:`rounded-xl border p-3.5 space-y-2.5 transition-all shadow-sm ${l.border} ${l.bg}`,children:[a.title&&r.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b border-border/40",children:[r.jsx("span",{className:"p-1 rounded-md bg-bg-card/80 border border-border/50 shrink-0",children:l.icon}),r.jsx("h4",{className:"font-bold text-xs sm:text-sm font-mono text-text-primary tracking-tight",children:Ke(a.title)})]}),r.jsx("div",{className:"space-y-2",children:a.items.map((c,d)=>{const h=c.match(/^[-*•]\s*\*\*([^*]+?)\*\*[:\s]+(.*)$/);if(h){const m=h[1].trim(),x=h[2].trim();return r.jsxs("div",{className:"flex items-start gap-2 text-xs sm:text-[13px] leading-relaxed group",children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full mt-2 shrink-0 ${l.dot}`}),r.jsxs("div",{className:"flex-1",children:[r.jsxs("span",{className:"font-semibold text-purple-200 mr-1.5",children:[m,":"]}),r.jsx("span",{className:"text-text-primary/95",children:Ke(x)})]})]},d)}if(c.startsWith("- ")||c.startsWith("* ")||c.startsWith("• ")){const m=c.replace(/^[-*•]\s+/,"").trim();return r.jsxs("div",{className:"flex items-start gap-2 text-xs sm:text-[13px] leading-relaxed",children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full mt-2 shrink-0 ${l.dot}`}),r.jsx("div",{className:"flex-1 text-text-primary/95",children:Ke(m)})]},d)}const u=c.match(/^(\d+)\.\s+(.*)$/);if(u){const m=u[1],x=u[2].trim(),b=x.match(/^\*\*([^*]+?)\*\*[:\s]+(.*)$/);if(b){const f=b[1].trim(),g=b[2].trim();return r.jsxs("div",{className:"flex items-start gap-2.5 text-xs sm:text-[13px] leading-relaxed p-2 rounded-lg bg-bg-card/50 border border-border/50",children:[r.jsx("span",{className:"px-1.5 py-0.2 rounded text-[10px] font-mono font-bold bg-bg-elevated text-purple-300 border border-border/60 shrink-0 mt-0.5",children:m}),r.jsxs("div",{className:"flex-1",children:[r.jsxs("span",{className:"font-bold text-purple-200 mr-1.5",children:[f,":"]}),r.jsx("span",{className:"text-text-primary/95",children:Ke(g)})]})]},d)}return r.jsxs("div",{className:"flex items-start gap-2.5 text-xs sm:text-[13px] leading-relaxed p-2 rounded-lg bg-bg-card/50 border border-border/50",children:[r.jsx("span",{className:"px-1.5 py-0.2 rounded text-[10px] font-mono font-bold bg-bg-elevated text-purple-300 border border-border/60 shrink-0 mt-0.5",children:m}),r.jsx("div",{className:"flex-1 text-text-primary/95",children:Ke(x)})]},d)}return c.startsWith("⚠️")||c.startsWith("🚨")||c.toUpperCase().startsWith("WARNING:")?r.jsxs("div",{className:"p-2.5 rounded-lg bg-amber-500/10 border border-amber-500/30 text-amber-200 text-xs sm:text-[12px] flex items-start gap-2",children:[r.jsx(ve,{size:14,className:"text-amber-400 shrink-0 mt-0.5"}),r.jsx("div",{className:"leading-snug",children:Ke(c)})]},d):r.jsx("p",{className:"text-text-primary/95 leading-relaxed",children:Ke(c)},d)})})]},a.id||o)})})}const eu=y.lazy(()=>xt(()=>import("./GlobalAISettingsModal-BOzCh0qM.js"),__vite__mapDeps([5,1,2,3])).then(s=>({default:s.GlobalAISettingsModal}))),ln=[{label:"⚡ Setup Scalp 15m",prompt:"Berikan analisa scalping timeframe 15m, apakah ada momentum masuk saat ini dan di level berapa entry amannya?"},{label:"🧲 Cek Likuidasi & Trap",prompt:"Analisa kolam likuidasi (magnet harga) dan apakah ada jebakan leverage trap antara Spot vs Futures CVD?"},{label:"🛡️ Validasi Fake Breakout",prompt:"Periksa apakah ada tanda-tanda manipulasi harga, fake pump/dump, atau wick sweep pada pair ini?"},{label:"📋 Rencana Trading Lengkap",prompt:"Buatkan rencana trading institusional: Entry Zone terkonfirmasi, Stop Loss ketat, Take Profit 1 & 2, serta kondisi pembatalan setup."}];function tu(s){if(!s)return"bg-gray-500/20 text-gray-300 border-gray-500/30";const e=s.toUpperCase();return e.includes("STRONG LONG")||e.includes("STRONG BUY")?"bg-emerald-500/20 text-emerald-300 border-emerald-500/40":e.includes("LONG")?"bg-signal-long/20 text-signal-long border-signal-long/30":e.includes("STRONG SHORT")||e.includes("STRONG SELL")?"bg-rose-500/20 text-rose-300 border-rose-500/40":e.includes("SHORT")?"bg-signal-short/20 text-signal-short border-signal-short/30":"bg-amber-500/20 text-amber-300 border-amber-500/30"}function su({initialSymbol:s="BTCUSDT",onSelectSymbol:e}){const{data:t=[],isLoading:i}=us(),{data:n=[]}=li(),{settings:a,isConfigured:o}=ci(),{toast:l}=bt(),c=y.useMemo(()=>t.filter(_=>_.is_active),[t]),[d,h]=y.useState(()=>s&&t.some(_=>_.symbol===s)?s:c[0]?.symbol||"BTCUSDT"),u=_=>{h(_),e&&e(_)};y.useEffect(()=>{s&&s!==d&&h(s)},[s]);const[m,x]=y.useState(""),[b,f]=y.useState("ALL"),[g,p]=y.useState({}),[v,S]=y.useState(""),[j,k]=y.useState(!1),[C,E]=y.useState(null),[T,D]=y.useState({}),[O,M]=y.useState({}),R=_=>{M(B=>({...B,[_]:!B[_]}))},L=y.useRef(null),$=y.useMemo(()=>n.find(_=>_.symbol===d),[n,d]),z=y.useMemo(()=>new Map(n.map(_=>[_.symbol,_])),[n]),V=y.useMemo(()=>c.filter(_=>{if(!(_.symbol.toLowerCase().includes(m.toLowerCase().trim())||_.display_name.toLowerCase().includes(m.toLowerCase().trim())))return!1;const Y=z.get(_.symbol);return b==="SPOT_ONLY"?Y?.has_spot===!0:b==="PERP_ONLY"?Y?.has_spot===!1:b==="HOT"?(Y?.conviction??0)>=4:b==="LONG"?Y?.direction==="LONG":b==="SHORT"?Y?.direction==="SHORT":!0}),[c,m,b,z]),q=g[d]||{messages:[],isLoading:!1,error:null};y.useEffect(()=>{L.current?.scrollIntoView({behavior:"smooth"})},[q.messages.length,q.isLoading]);const Z=async(_,B=!1)=>{const Y=(_!==void 0?_:v).trim();if(!Y&&q.messages.length>0&&!B)return;if(!o){k(!0),l("Silakan masukkan API Key AI Anda terlebih dahulu","error");return}const F=`user-${Date.now()}`,le=Y?{id:F,role:"user",content:Y,timestamp:new Date().toLocaleTimeString("id-ID",{hour:"2-digit",minute:"2-digit"})}:null;p(K=>{const te=K[d]||{messages:[],isLoading:!1,error:null};return{...K,[d]:{...te,messages:le?[...te.messages,le]:te.messages,isLoading:!0,error:null}}}),_||S("");try{const K=await qh.analyze({symbol:d,provider:a.provider,model:a.model,api_key:a.api_key,base_url:a.provider==="custom"?a.base_url:void 0,question:Y||void 0,force_refresh:B,max_tokens:a.max_tokens}),te={id:`ai-${Date.now()}`,role:"assistant",content:K.analysis,timestamp:new Date().toLocaleTimeString("id-ID",{hour:"2-digit",minute:"2-digit"}),bias:K.bias,model:K.model,isCached:K.is_cached,cacheAgeSeconds:K.cache_age_seconds,dataSnapshot:K.data_snapshot};p(be=>{const Se=be[d]||{messages:[],isLoading:!1,error:null};return{...be,[d]:{...Se,messages:[...Se.messages,te],isLoading:!1,error:null}}})}catch(K){const te=K?.response?.data?.detail||K?.message||"Gagal menghubungi server AI";p(be=>{const Se=be[d]||{messages:[],isLoading:!1,error:null};return{...be,[d]:{...Se,isLoading:!1,error:te}}}),l(te,"error")}},ae=()=>{p(_=>({..._,[d]:{messages:[],isLoading:!1,error:null}})),l(`Riwayat tanya jawab untuk ${d} dibersihkan`,"success")},A=(_,B)=>{navigator.clipboard.writeText(_),E(B),l("Teks analisa berhasil disalin ke clipboard","success"),setTimeout(()=>E(null),2e3)},H=_=>{D(B=>({...B,[_]:!B[_]}))};return r.jsxs("div",{className:"flex flex-1 h-[calc(100vh-3.5rem)] overflow-hidden bg-bg-primary",children:[r.jsxs("aside",{className:"hidden md:flex w-64 lg:w-72 flex-col border-r border-border bg-bg-card shrink-0 select-none",children:[r.jsxs("div",{className:"p-3 border-b border-border space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("span",{className:"text-xs font-bold text-text-secondary uppercase tracking-wider flex items-center gap-1.5",children:[r.jsx(Be,{size:14,className:"text-purple-400"}),"Pilih Pair Analisa"]}),r.jsxs("span",{className:"text-[10px] font-mono text-purple-400 bg-purple-500/10 px-1.5 py-0.5 rounded border border-purple-500/20",children:[c.length," Pair"]})]}),r.jsxs("div",{className:"relative",children:[r.jsx(Zs,{size:13,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-text-muted"}),r.jsx("input",{type:"text",value:m,onChange:_=>x(_.target.value),placeholder:"Cari pair (e.g. BTC, SOL)...",className:"w-full bg-bg-elevated border border-border rounded-lg pl-8 pr-2.5 py-1.5 text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500/50"})]}),r.jsxs("div",{className:"flex items-center gap-1 overflow-x-auto no-scrollbar pt-0.5",children:[r.jsx("button",{onClick:()=>f("ALL"),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 ${b==="ALL"?"bg-purple-600 text-white":"bg-bg-elevated text-text-secondary hover:text-text-primary"}`,children:"Semua"}),r.jsxs("button",{onClick:()=>f("SPOT_ONLY"),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 flex items-center gap-1 ${b==="SPOT_ONLY"?"bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-semibold":"bg-bg-elevated text-text-secondary hover:text-emerald-300"}`,title:"Hanya tampilkan pair yang memiliki pasar Spot riil",children:[r.jsx(Tt,{size:10,className:"text-emerald-400"}),"Aman"]}),r.jsxs("button",{onClick:()=>f("PERP_ONLY"),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 flex items-center gap-1 ${b==="PERP_ONLY"?"bg-amber-500/20 text-amber-300 border border-amber-500/40 font-semibold":"bg-bg-elevated text-text-secondary hover:text-amber-300"}`,title:"Hanya tampilkan pair PERP-ONLY tanpa Spot (Rawan manipulasi bandar)",children:[r.jsx(ve,{size:10,className:"text-amber-400"}),"Rawan"]}),r.jsxs("button",{onClick:()=>f("HOT"),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 flex items-center gap-1 ${b==="HOT"?"bg-amber-500/20 text-amber-300 border border-amber-500/40":"bg-bg-elevated text-text-secondary hover:text-amber-300"}`,children:[r.jsx(ts,{size:10}),"Hot ≥4"]}),r.jsxs("button",{onClick:()=>f("LONG"),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 flex items-center gap-1 ${b==="LONG"?"bg-signal-long/20 text-signal-long border border-signal-long/40":"bg-bg-elevated text-text-secondary hover:text-signal-long"}`,children:[r.jsx(aa,{size:10}),"Long"]}),r.jsxs("button",{onClick:()=>f("SHORT"),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 flex items-center gap-1 ${b==="SHORT"?"bg-signal-short/20 text-signal-short border border-signal-short/40":"bg-bg-elevated text-text-secondary hover:text-signal-short"}`,children:[r.jsx(oa,{size:10}),"Short"]})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto custom-scrollbar p-2 space-y-1",children:[i&&r.jsx("div",{className:"p-4 text-center text-xs text-text-muted",children:"Memuat daftar pair..."}),!i&&V.length===0&&r.jsx("div",{className:"p-4 text-center text-xs text-text-muted",children:"Tidak ada pair yang cocok"}),V.map(_=>{const B=z.get(_.symbol),Y=_.symbol===d,F=g[_.symbol]?.messages?.length||0,le=B?.direction==="LONG"?"text-signal-long bg-signal-long/10 border-signal-long/30":B?.direction==="SHORT"?"text-signal-short bg-signal-short/10 border-signal-short/30":"text-text-muted bg-bg-elevated border-border";return r.jsxs("button",{type:"button",onClick:()=>u(_.symbol),className:`w-full flex items-center justify-between p-2 rounded-xl text-xs transition-all text-left ${Y?"bg-purple-600/15 border border-purple-500/50 shadow-sm text-text-primary":"hover:bg-bg-elevated/70 border border-transparent text-text-secondary hover:text-text-primary"}`,children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${B?.direction==="LONG"?"bg-signal-long shadow-sm shadow-signal-long/50":B?.direction==="SHORT"?"bg-signal-short shadow-sm shadow-signal-short/50":"bg-gray-500"}`}),r.jsxs("div",{className:"truncate",children:[r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("p",{className:`font-mono font-bold truncate ${Y?"text-purple-300":"text-text-primary"}`,children:_.display_name}),B?.has_spot===!1&&r.jsx("span",{className:"text-[8px] px-1 py-0.5 rounded bg-amber-500/20 text-amber-300 font-mono font-bold shrink-0",title:"Rawan Bandar (Perp Only)",children:"⚠️ RAWAN"}),B?.has_spot===!0&&r.jsx("span",{className:"text-[8px] px-1 py-0.5 rounded bg-emerald-500/15 text-emerald-300 font-mono font-semibold shrink-0",title:"Aman (Spot Backed)",children:"🛡️ AMAN"})]}),r.jsx("p",{className:"text-[10px] text-text-muted",children:B?.trade_levels?.entry_price?`$${B.trade_levels.entry_price}`:B?.active_timeframe||"Perps"})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[F>0&&r.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 font-mono",children:F}),B&&r.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono font-bold border ${le}`,children:[B.conviction,"/10"]})]})]},_.symbol)})]})]}),r.jsxs("section",{className:"flex-1 flex flex-col h-full overflow-hidden bg-bg-primary",children:[r.jsxs("div",{className:"px-3 sm:px-5 py-2.5 border-b border-border bg-bg-card flex flex-col sm:flex-row sm:items-center justify-between gap-2 shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("div",{className:"p-2 rounded-xl bg-purple-500/15 border border-purple-500/30 text-purple-400 shrink-0",children:r.jsx(Be,{size:18})}),r.jsxs("div",{className:"min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("h2",{className:"font-mono font-bold text-sm sm:text-base text-text-primary truncate hidden md:inline",children:d}),r.jsxs("div",{className:"relative md:hidden inline-flex items-center",children:[r.jsx("select",{value:d,onChange:_=>u(_.target.value),className:"opacity-0 absolute inset-0 w-full h-full cursor-pointer z-10","aria-label":"Pilih Trading Pair",children:c.map(_=>{const B=z.get(_.symbol),Y=B?.direction==="LONG"?"🟢":B?.direction==="SHORT"?"🔴":"⚪";return r.jsxs("option",{value:_.symbol,children:[Y," ",_.display_name," — ",B?.direction||"WAIT"," (",B?.conviction||0,"/10)"]},_.symbol)})}),r.jsxs("button",{type:"button",className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-bg-elevated border border-purple-500/40 text-xs font-mono font-bold text-purple-300 shadow-sm active:scale-95",title:"Ketuk untuk ganti pair",children:[r.jsx("span",{children:d}),r.jsx(_t,{size:12,className:"text-purple-400"})]})]}),$?.has_spot===!1&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/40 flex items-center gap-1 shrink-0",title:"Aset RAWAN BANDAR: Kontrak Perp-Only tanpa pasar Spot riil.",children:[r.jsx(ve,{size:10,className:"text-amber-400"}),"⚠️ Perp Only"]}),$?.has_spot===!0&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-medium bg-emerald-500/15 text-emerald-400 border border-emerald-500/30 flex items-center gap-1 shrink-0",title:"Aset AMAN: Memiliki pasar Spot riil di bursa.",children:[r.jsx(Tt,{size:10,className:"text-emerald-400"}),"🛡️ Spot"]}),$&&r.jsxs("span",{className:`px-2 py-0.5 rounded-full text-[10px] font-mono font-bold border ${$.direction==="LONG"?"bg-signal-long/15 text-signal-long border-signal-long/30":$.direction==="SHORT"?"bg-signal-short/15 text-signal-short border-signal-short/30":"bg-gray-500/15 text-text-muted border-border"}`,children:[$.direction," • ",$.conviction,"/10"]}),$?.active_timeframe&&r.jsxs("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-bg-elevated border border-border text-text-muted",children:["TF: ",$.active_timeframe.toUpperCase()]})]}),r.jsx("p",{className:"text-[10px] text-text-muted truncate",children:$?.quick_verdict||"Data live bursa tersambung & siap dianalisa AI"})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 self-end sm:self-auto shrink-0",children:[r.jsxs("button",{type:"button",onClick:()=>Z(void 0,!0),disabled:q.isLoading,className:"flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-medium border border-border bg-bg-elevated hover:bg-bg-card text-text-secondary hover:text-text-primary transition-colors disabled:opacity-50",title:"Paksa hitung ulang analisa dengan token baru",children:[r.jsx(Pe,{size:11,className:q.isLoading?"animate-spin":""}),r.jsx("span",{className:"hidden xs:inline",children:"Analisa Ulang"})]}),q.messages.length>0&&r.jsx("button",{type:"button",onClick:ae,className:"p-1.5 rounded-lg border border-border bg-bg-elevated hover:bg-red-500/20 hover:text-red-300 text-text-muted transition-colors",title:"Bersihkan riwayat percakapan pair ini",children:r.jsx(Qt,{size:13})}),r.jsxs("button",{type:"button",onClick:()=>k(!0),className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs border border-purple-500/30 bg-purple-500/10 hover:bg-purple-500/20 text-purple-200 transition-colors",title:"Atur Model AI & API Key",children:[r.jsx(dr,{size:12,className:"text-purple-400"}),r.jsx("span",{className:"font-mono text-[11px] truncate max-w-[100px]",children:a.model.split("/")[1]||a.model})]})]})]}),r.jsxs("div",{className:"md:hidden flex items-center gap-1.5 px-3 py-2 bg-bg-elevated/80 border-b border-border overflow-x-auto no-scrollbar shrink-0",children:[r.jsx("span",{className:"text-[10px] text-text-muted uppercase font-semibold shrink-0",children:"Pair:"}),c.map(_=>{const B=_.symbol===d,Y=z.get(_.symbol);return r.jsxs("button",{onClick:()=>u(_.symbol),className:`px-2.5 py-1 rounded-lg text-xs font-mono shrink-0 transition-all ${B?"bg-purple-600 text-white font-bold shadow-sm":"bg-bg-card border border-border text-text-secondary hover:text-text-primary"}`,children:[_.symbol.replace("USDT",""),Y&&r.jsx("span",{className:`ml-1 text-[10px] ${Y.direction==="LONG"?"text-signal-long":Y.direction==="SHORT"?"text-signal-short":"text-gray-400"}`,children:Y.conviction})]},_.symbol)})]}),$?.has_spot===!1&&r.jsxs("div",{className:"mx-3 sm:mx-5 mt-3 p-2.5 rounded-xl bg-amber-500/15 border border-amber-500/30 text-xs text-amber-200 flex items-start gap-2.5 shrink-0 shadow-sm animate-fade-in",children:[r.jsx(ve,{size:15,className:"text-amber-400 shrink-0 mt-0.5"}),r.jsxs("div",{className:"leading-snug",children:[r.jsxs("span",{className:"font-bold text-amber-200",children:["⚠️ PERINGATAN RISIKO BANDAR (",d," adalah PERP-ONLY):"]}),r.jsx("p",{className:"text-[11px] text-amber-300/90 mt-0.5 leading-relaxed",children:"Koin ini tidak memiliki pasar Spot di bursa. Analisa tetap lengkap, namun harga rawan dimanipulasi wick sweep. Wajib pasang Stop Loss ketat!"})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-3 sm:p-5 space-y-4 custom-scrollbar",children:[q.messages.length===0&&!q.isLoading&&r.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[50vh] text-center max-w-xl mx-auto space-y-4 p-4 animate-fade-in",children:[r.jsx("div",{className:"w-14 h-14 rounded-2xl bg-purple-500/10 border border-purple-500/20 flex items-center justify-center text-purple-400 shadow-lg shadow-purple-500/10",children:r.jsx(Fe,{size:28})}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("h3",{className:"text-base sm:text-lg font-bold text-text-primary",children:["Damian — AI Quant Partner untuk ",d]}),r.jsx("p",{className:"text-xs text-text-secondary max-w-md mx-auto leading-relaxed",children:"Tanyakan setup trading, validasi likuidasi, atau jalankan analisa menyeluruh. Data multi-exchange (Binance, Bybit, OKX, Hyperliquid, Spot vs Fut CVD) akan disintesis otomatis secara objektif dan anti-halusinasi."})]}),r.jsx("div",{className:"pt-2",children:r.jsxs(se,{variant:"primary",size:"md",onClick:()=>Z(),icon:r.jsx(Oe,{size:14}),className:"bg-purple-600 hover:bg-purple-500 text-white shadow-lg shadow-purple-500/25 px-5 py-2.5 rounded-xl font-semibold text-xs sm:text-sm",children:["Mulai Analisa Lengkap ",d]})}),r.jsxs("div",{className:"pt-4 w-full",children:[r.jsx("p",{className:"text-[11px] font-semibold text-text-muted uppercase tracking-wider mb-2",children:"Atau Pilih Topik Cepat:"}),r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-left",children:ln.map((_,B)=>r.jsx("button",{type:"button",onClick:()=>Z(_.prompt),className:"p-2.5 rounded-xl border border-border bg-bg-card hover:bg-bg-elevated hover:border-purple-500/40 text-xs transition-all flex items-start gap-2 text-left group",children:r.jsx("span",{className:"font-semibold text-text-primary group-hover:text-purple-300",children:_.label})},B))})]})]}),q.messages.map(_=>_.role==="user"?r.jsx("div",{className:"flex justify-end animate-fade-in",children:r.jsxs("div",{className:"max-w-[85%] sm:max-w-[75%] rounded-2xl rounded-tr-sm bg-purple-600 text-white p-3.5 shadow-md shadow-purple-600/10 space-y-1",children:[r.jsx("p",{className:"text-xs sm:text-sm font-sans",children:_.content}),r.jsx("p",{className:"text-[10px] text-purple-200 text-right",children:_.timestamp})]})},_.id):r.jsx("div",{className:"flex flex-col space-y-2 animate-fade-in max-w-[95%] sm:max-w-[90%]",children:r.jsxs("div",{className:"rounded-2xl rounded-tl-sm bg-bg-card border border-border/90 p-4 sm:p-5 space-y-3.5 shadow-sm",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pb-2.5 border-b border-border/60",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"p-1 rounded-md bg-purple-500/20 text-purple-400",children:r.jsx(Be,{size:14})}),r.jsx("span",{className:"text-xs font-bold font-mono text-purple-300",children:/EXECUTIVE VERDICT|Actionable Trade Setup|Rencana Trading/i.test(_.content)?"Damian Quantitative Digest":"Damian Quant Partner"}),_.bias&&r.jsx("span",{className:`px-2 py-0.5 rounded text-[11px] font-mono font-bold border ${tu(_.bias)}`,children:_.bias})]}),r.jsxs("div",{className:"flex items-center gap-1.5",children:[_.isCached&&r.jsx("span",{className:"text-[10px] font-mono text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-1.5 py-0.5 rounded",children:"Hemat Token (Cache)"}),r.jsx("button",{type:"button",onClick:()=>R(_.id),className:"px-2 py-1 rounded text-[10px] border border-border text-text-secondary hover:text-purple-300 flex items-center gap-1 hover:bg-bg-elevated transition-colors",title:O[_.id]?"Tampilkan narasi teks lengkap":"Ciutkan narasi teks analisa",children:O[_.id]?r.jsxs(r.Fragment,{children:[r.jsx(_t,{size:11}),r.jsx("span",{children:"Buka Teks"})]}):r.jsxs(r.Fragment,{children:[r.jsx(Us,{size:11}),r.jsx("span",{children:"Ciutkan Teks"})]})}),r.jsx("button",{type:"button",onClick:()=>A(_.content,_.id),className:"px-2 py-1 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:"Salin Analisa Lengkap",children:C===_.id?r.jsxs(r.Fragment,{children:[r.jsx(at,{size:11,className:"text-signal-long"}),r.jsx("span",{className:"text-signal-long",children:"Tersalin"})]}):r.jsxs(r.Fragment,{children:[r.jsx(es,{size:11}),r.jsx("span",{children:"Salin"})]})})]})]}),!O[_.id]&&r.jsx(Ya,{content:_.content}),r.jsx(Jh,{symbol:d,content:_.content,bias:_.bias,dataSnapshot:_.dataSnapshot,tradeLevels:$?.trade_levels,modelUsed:_.model}),_.dataSnapshot&&r.jsxs("div",{className:"pt-2 border-t border-border/50",children:[r.jsxs("button",{type:"button",onClick:()=>H(_.id),className:"text-[11px] text-text-secondary hover:text-purple-300 flex items-center gap-1 transition-colors",children:[r.jsx(ei,{size:11}),r.jsx("span",{children:T[_.id]?"Sembunyikan Telemetry Data Mentah":"Lihat Telemetry Data Mentah yang Dikirim ke AI"}),T[_.id]?r.jsx(Us,{size:12}):r.jsx(_t,{size:12})]}),T[_.id]&&r.jsxs("div",{className:"mt-2 p-3 rounded-xl bg-bg-elevated border border-border/80 text-[10px] font-mono grid grid-cols-2 sm:grid-cols-4 gap-2.5 animate-fade-in",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"MARK PRICE"}),r.jsx("span",{className:"text-text-primary font-bold",children:_.dataSnapshot.mark_price_str||`$${_.dataSnapshot.mark_price}`})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"MULTI-VENUE SPREAD"}),r.jsxs("span",{className:"text-text-primary",children:[(_.dataSnapshot.triangulation_spread_pct??0).toFixed(4),"%"]})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"BINANCE FR"}),r.jsx("span",{className:"text-text-primary",children:_.dataSnapshot.binance_fr})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"BYBIT FR"}),r.jsx("span",{className:"text-text-primary",children:_.dataSnapshot.bybit_fr})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"OKX FR"}),r.jsx("span",{className:"text-text-primary",children:_.dataSnapshot.okx_fr})]}),_.dataSnapshot.bitget_fr&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"BITGET FR"}),r.jsx("span",{className:"text-text-primary",children:_.dataSnapshot.bitget_fr})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"HYPERLIQUID FR"}),r.jsx("span",{className:"text-text-primary",children:_.dataSnapshot.hyperliquid_fr})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"SPOT CVD"}),r.jsx("span",{className:"text-text-primary",children:_.dataSnapshot.spot_cvd})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"FUTURES CVD"}),r.jsx("span",{className:"text-text-primary",children:_.dataSnapshot.futures_cvd})]}),r.jsxs("div",{className:"col-span-2",children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"LIQUIDATION MAGNETS"}),r.jsxs("span",{className:"text-text-primary",children:[_.dataSnapshot.upper_magnet," / ",_.dataSnapshot.lower_magnet]})]}),r.jsxs("div",{className:"col-span-2",children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"ORDERBOOK PRESSURE"}),r.jsx("span",{className:"text-text-primary",children:_.dataSnapshot.resting_pressure})]}),_.dataSnapshot.lead_lag_spread_bps!=null&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"LEAD-LAG SPREAD"}),r.jsxs("span",{className:"text-cyan-300",children:[(_.dataSnapshot.lead_lag_spread_bps??0).toFixed(1)," bps (",_.dataSnapshot.leading_exchange?.toUpperCase()||"BALANCED",")"]})]}),_.dataSnapshot.funding_countdown&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"SETTLEMENT"}),r.jsx("span",{className:_.dataSnapshot.is_settlement_imminent?"text-amber-400 font-bold":"text-text-primary",children:_.dataSnapshot.funding_countdown})]}),_.dataSnapshot.range_24h_pct!=null&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"24H RANGE"}),r.jsxs("span",{className:"text-text-primary",children:[(_.dataSnapshot.range_24h_pct??0).toFixed(2),"% (",(_.dataSnapshot.range_position_pct??0).toFixed(0),"% pos)"]})]}),_.dataSnapshot.whale_buy_count!=null&&_.dataSnapshot.whale_sell_count!=null&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"WHALE BLOCKS"}),r.jsxs("span",{className:"text-emerald-400",children:[_.dataSnapshot.whale_buy_count,"B / ",_.dataSnapshot.whale_sell_count,"S"]})]})]})]}),r.jsxs("div",{className:"flex items-center justify-between text-[10px] text-text-muted pt-1",children:[r.jsxs("span",{children:["Model: ",_.model||a.model]}),r.jsx("span",{children:_.timestamp})]})]})},_.id)),q.isLoading&&r.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-2xl bg-bg-card border border-purple-500/20 max-w-md animate-fade-in",children:[r.jsx("div",{className:"w-8 h-8 rounded-full border-2 border-purple-500/30 border-t-purple-500 animate-spin shrink-0"}),r.jsxs("div",{className:"space-y-1",children:[r.jsxs("p",{className:"text-xs font-bold text-text-primary flex items-center gap-1.5",children:[r.jsx(Fe,{size:13,className:"text-purple-400 animate-pulse"}),"Menganalisa Aliran Modal ",d,"..."]}),r.jsxs("p",{className:"text-[10px] text-text-muted",children:["Menyintesis data orderbook, likuidasi, Spot vs Futures CVD ke ",a.model,"..."]})]})]}),q.error&&!q.isLoading&&r.jsxs("div",{className:"p-3.5 rounded-xl bg-red-500/10 border border-red-500/30 flex items-start gap-2.5 text-xs text-red-200",children:[r.jsx(or,{size:16,className:"text-red-400 shrink-0 mt-0.5"}),r.jsxs("div",{className:"space-y-1 flex-1",children:[r.jsx("p",{className:"font-bold text-red-300",children:"Gagal Mendapatkan Analisa AI"}),r.jsx("p",{className:"text-[11px] text-red-200/90",children:q.error}),r.jsxs("div",{className:"pt-1 flex items-center gap-2",children:[r.jsx("button",{onClick:()=>Z(void 0,!0),className:"text-[10px] px-2 py-0.5 rounded bg-red-500/20 hover:bg-red-500/30 text-red-100 font-semibold border border-red-500/40",children:"Coba Lagi"}),r.jsx("button",{onClick:()=>k(!0),className:"text-[10px] text-purple-300 hover:underline",children:"Buka Pengaturan AI"})]})]})]}),r.jsx("div",{ref:L})]}),r.jsxs("div",{className:"p-3 sm:p-4 border-t border-border bg-bg-card/95 shrink-0 pb-16 md:pb-4",children:[q.messages.length>0&&r.jsx("div",{className:"flex items-center gap-1.5 overflow-x-auto no-scrollbar pb-2 mb-1",children:ln.map((_,B)=>r.jsx("button",{type:"button",onClick:()=>Z(_.prompt),disabled:q.isLoading,className:"px-2.5 py-1 rounded-lg text-[10px] font-medium bg-bg-elevated hover:bg-purple-600/20 hover:text-purple-300 border border-border text-text-secondary transition-all shrink-0 disabled:opacity-50",children:_.label},B))}),r.jsxs("form",{onSubmit:_=>{_.preventDefault(),Z()},className:"flex items-center gap-2",children:[r.jsx("input",{type:"text",value:v,onChange:_=>S(_.target.value),placeholder:`Tanyakan analisa teknikal, validasi trap, atau scalping ke Damian untuk ${d}...`,disabled:q.isLoading,className:"flex-1 bg-bg-elevated border border-border focus:border-purple-500/60 rounded-xl px-3.5 py-2.5 text-xs sm:text-sm text-text-primary placeholder:text-text-muted focus:outline-none transition-colors"}),r.jsx(se,{type:"submit",variant:"primary",size:"md",loading:q.isLoading,disabled:q.isLoading||!v.trim(),icon:r.jsx(Qo,{size:14}),className:"bg-purple-600 hover:bg-purple-500 text-white rounded-xl px-4 py-2.5 shadow-sm shadow-purple-600/30 shrink-0",children:r.jsx("span",{className:"hidden xs:inline",children:"Kirim"})})]})]})]}),j&&r.jsx(y.Suspense,{fallback:null,children:r.jsx(eu,{isOpen:j,onClose:()=>k(!1)})})]})}const iu=[{id:"WICK_HUNT",label:"⚡ Jarum Wick Hunt",desc:"SL tersapu jarum tipis lalu harga langsung mantul balik"},{id:"FALSE_BREAKOUT",label:"🛑 False Breakout",desc:"Terjebak beli di pucuk resisten atau sell di dasar support"},{id:"BTC_DUMP",label:"📉 Market / BTC Drag",desc:"Terseret kejatuhan pasar global / dump mendadak Bitcoin"},{id:"TREND_REVERSAL",label:"🔄 Trend Reversal (HTF)",desc:"Struktur tren HTF (1H/4H) patah berbalik arah melawan posisi"},{id:"PREMATURE_ENTRY",label:"⚠️ Entry Prematur",desc:"Masuk sebelum candle konfirmasi / pullback selesai terbentuk"},{id:"OTHER",label:"📝 Alasan Lainnya",desc:"Penyebab teknis atau faktor pasar lainnya"}];function ru({onNavigateToAI:s,isActiveTab:e}){const[t,i]=y.useState([]),[n,a]=y.useState({total:0,hit_tp:0,hit_sl:0,pending:0,cancelled:0,completed:0,win_rate_pct:0,unaudited_sl_count:0}),[o,l]=y.useState([]),[c,d]=y.useState(!0),[h,u]=y.useState("ALL"),[m,x]=y.useState(""),[b,f]=y.useState(null),[g,p]=y.useState(""),[v,S]=y.useState("WICK_HUNT"),[j,k]=y.useState(""),[C,E]=y.useState(!1),[T,D]=y.useState({}),[O,M]=y.useState(null),[R,L]=y.useState(!1),[$,z]=y.useState(!1),[V,q]=y.useState(""),[Z,ae]=y.useState(!1),{settings:A}=ci(),{toast:H}=bt(),_=y.useMemo(()=>{let N;switch(A.provider){case"gemini":N=Dh;break;case"openai":N=Bh;break;case"openrouter":N=Fh;break;case"groq":N=Uh;break;case"vikey":default:N=$h;break}return A.model&&!N.some(Q=>Q.id===A.model)?[...N,{id:A.model,label:`Custom: ${A.model}`}]:N},[A.provider,A.model]);y.useEffect(()=>{A.model&&_.some(N=>N.id===A.model)?q(A.model):_.length>0&&q(_[0].id)},[A.provider,A.model,_]);const B=async(N=!1)=>{N||d(!0);try{const[Q,J,ee]=await Promise.all([Ae.getEntries("ALL",100),Ae.getStats(),Ae.getMemory()]);i(Q.entries),a(J),l(ee.memories)}catch(Q){N||H(Q.message||"Gagal memuat data Jurnal Trade","error")}finally{N||d(!1)}};y.useEffect(()=>{B(),A.model&&q(A.model)},[]),y.useEffect(()=>{e&&B(!0)},[e]),y.useEffect(()=>{const N=Q=>{const J=Q?.detail;J&&J.id?(i(ee=>J.deleted_id?ee.filter(X=>X.id!==J.deleted_id):ee.some(X=>X.id===J.id)?ee.map(X=>X.id===J.id?{...X,...J}:X):[J,...ee]),Ae.getStats().then(a).catch(()=>{})):B(!0)};return window.addEventListener("journal-updated",N),()=>{window.removeEventListener("journal-updated",N)}},[]);const Y=y.useMemo(()=>t.filter(N=>N.symbol.toLowerCase().includes(m.toLowerCase().trim())||N.bias.toLowerCase().includes(m.toLowerCase().trim())?h==="ALL"?!0:N.status===h:!1),[t,m,h]),F=N=>{try{const Q=new Date(N).getTime();if(!Number.isFinite(Q))return{seconds:0,formatted:"N/A"};const J=Date.now(),ee=Math.max(0,Math.floor((J-Q)/1e3)),W=Math.floor(ee/3600),X=Math.floor(ee%3600/60);let ke=`${X} menit`;return W>0&&(ke=`${W} jam ${X} menit`),{seconds:ee,formatted:ke}}catch{return{seconds:0,formatted:"N/A"}}},le=N=>{D(Q=>({...Q,[N]:!Q[N]}))},K=(N,Q)=>{f({entry:N,targetStatus:Q}),p(N.outcome_note||""),S(N.failure_tag||(Q==="HIT_SL"?"WICK_HUNT":"")),k(N.exit_price?String(N.exit_price):"")},te=async()=>{if(b){E(!0);try{const N=F(b.entry.created_at),Q=j.trim()?parseFloat(j.trim()):void 0,J=await Ae.updateStatus(b.entry.id,b.targetStatus,g.trim()||void 0,b.targetStatus==="HIT_SL"?v||"OTHER":void 0,Q&&!isNaN(Q)?Q:void 0,N.seconds>0?N.seconds:void 0);i(W=>W.map(X=>X.id===b.entry.id?J.entry:X)),a(J.stats),H({HIT_TP:"🟢 Berhasil HIT TP! Selamat atas cuan Anda!",HIT_SL:"🔴 Terkena Stop Loss. Diagnosa & telemetri dicatat untuk evaluasi Damian.",CANCELLED:"⚪ Sinyal dibatalkan / Breakeven."}[b.targetStatus],"info"),f(null)}catch(N){H(N.message||"Gagal memperbarui status","error")}finally{E(!1)}}},be=async N=>{try{const Q=await Ae.updateStatus(N.id,"PENDING");i(J=>J.map(ee=>ee.id===N.id?Q.entry:ee)),a(Q.stats),H(`[${N.symbol}] Status dikembalikan ke Sedang Berjalan (Pending)`,"info")}catch(Q){H(Q.message||"Gagal mengembalikan status","error")}},Se=N=>{M(N)},tt=async()=>{if(!O)return;L(!0);const N=O.symbol,Q=O.id;try{await Ae.deleteEntry(Q),i(J=>J.filter(ee=>ee.id!==Q)),M(null),H(`[${N}] Berhasil dihapus permanen dari Jurnal & Database.`,"info");try{const J=await Ae.getStats();a(J)}catch{}}catch(J){H(J.message||"Gagal menghapus catatan trade","error")}finally{L(!1)}},ge=async()=>{if(!A.api_key||!A.api_key.trim()){H("API Key AI belum terpasang. Harap masukkan API Key Anda di Pengaturan AI Universal (ikon gear di navbar atas).","error");return}ae(!0);try{const N=await Ae.synthesizeAudit({api_key:A.api_key,provider:A.provider,model:V||_[0]?.id,base_url:A.provider==="custom"?A.base_url:void 0,force:!0});H(N.message,"success"),z(!1),await B()}catch(N){H(N.message||"Gagal menjalankan audit memori Damian","error")}finally{ae(!1)}},we=N=>{switch(N){case"HIT_TP":return r.jsxs("span",{className:"px-2.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-emerald-500/15 border border-emerald-500/40 text-emerald-300 flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400"}),"HIT TP (CUAN)"]});case"HIT_SL":return r.jsxs("span",{className:"px-2.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-rose-500/15 border border-rose-500/40 text-rose-300 flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-rose-400"}),"HIT SL (RUGI)"]});case"CANCELLED":return r.jsx("span",{className:"px-2.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-gray-500/15 border border-gray-500/30 text-gray-400 flex items-center gap-1",children:"BATAL / BE"});default:return r.jsxs("span",{className:"px-2.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-amber-500/15 border border-amber-500/40 text-amber-300 flex items-center gap-1 animate-pulse",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400"}),"BERJALAN (PENDING)"]})}};return r.jsxs("div",{className:"flex-1 flex flex-col h-[calc(100vh-3.5rem)] overflow-y-auto custom-scrollbar bg-bg-primary select-none",children:[r.jsxs("div",{className:"max-w-6xl w-full mx-auto p-3 sm:p-5 space-y-4",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-2 border-b border-border/60",children:[r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.jsx("div",{className:"p-2 rounded-xl bg-purple-500/20 text-purple-300 border border-purple-500/30",children:r.jsx(Pr,{size:20})}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h2",{className:"text-base sm:text-lg font-bold text-text-primary font-mono tracking-tight",children:"Jurnal Trade Damian"}),r.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-purple-500/20 text-purple-300 border border-purple-500/30",children:"Continuous Learning"})]}),r.jsx("p",{className:"text-xs text-text-muted mt-0.5",children:"Konfirmasi hasil trade Anda. Damian belajar dari setiap Stop Loss untuk menyempurnakan analisa berikutnya."})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(se,{variant:"primary",size:"sm",onClick:()=>z(!0),icon:r.jsx(wt,{size:13}),className:`${n.unaudited_sl_count>=10?"bg-purple-600 hover:bg-purple-500 text-white shadow-lg shadow-purple-600/30 animate-pulse":"bg-purple-600/30 hover:bg-purple-600/50 text-purple-200 border border-purple-500/40"}`,children:[r.jsx("span",{children:"Audit Memori Damian"}),r.jsxs("span",{className:"px-1.5 py-0.2 rounded text-[10px] font-mono bg-bg-primary/60 font-bold ml-1",children:[n.unaudited_sl_count,"/10 SL"]})]}),r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>B(),loading:c,icon:r.jsx(Pe,{size:13}),title:"Perbarui data jurnal"})]})]}),r.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5",children:[r.jsxs("div",{className:"p-3.5 rounded-xl bg-bg-card border border-border flex flex-col justify-between space-y-1 shadow-sm",children:[r.jsx("span",{className:"text-[10px] text-text-muted uppercase font-bold tracking-wider",children:"WIN RATE REALISTIS"}),r.jsx("div",{className:"text-xl sm:text-2xl font-bold font-mono text-emerald-400",children:n.completed>0?`${n.win_rate_pct}%`:"N/A"}),r.jsxs("span",{className:"text-[10px] text-text-muted",children:["Dari ",n.completed," trade selesai (",n.hit_tp," TP vs ",n.hit_sl," SL)"]})]}),r.jsxs("div",{className:"p-3.5 rounded-xl bg-emerald-500/10 border border-emerald-500/20 flex flex-col justify-between space-y-1 shadow-sm",children:[r.jsxs("div",{className:"flex items-center justify-between text-emerald-300",children:[r.jsx("span",{className:"text-[10px] uppercase font-bold tracking-wider",children:"TOTAL HIT TP"}),r.jsx(Xe,{size:14,className:"text-emerald-400"})]}),r.jsxs("div",{className:"text-xl sm:text-2xl font-bold font-mono text-emerald-300",children:[n.hit_tp," Trade"]}),r.jsx("span",{className:"text-[10px] text-emerald-300/80",children:"Selesai Take Profit"})]}),r.jsxs("div",{className:"p-3.5 rounded-xl bg-rose-500/10 border border-rose-500/20 flex flex-col justify-between space-y-1 shadow-sm",children:[r.jsxs("div",{className:"flex items-center justify-between text-rose-300",children:[r.jsx("span",{className:"text-[10px] uppercase font-bold tracking-wider",children:"TOTAL STOP LOSS"}),r.jsx(Rt,{size:14,className:"text-rose-400"})]}),r.jsxs("div",{className:"text-xl sm:text-2xl font-bold font-mono text-rose-300",children:[n.hit_sl," Trade"]}),r.jsxs("span",{className:"text-[10px] text-rose-300/80",children:[n.unaudited_sl_count," belum diaudit"]})]}),r.jsxs("div",{className:"p-3.5 rounded-xl bg-amber-500/10 border border-amber-500/20 flex flex-col justify-between space-y-1 shadow-sm",children:[r.jsxs("div",{className:"flex items-center justify-between text-amber-300",children:[r.jsx("span",{className:"text-[10px] uppercase font-bold tracking-wider",children:"SEDANG BERJALAN"}),r.jsx(Fe,{size:14,className:"text-amber-400"})]}),r.jsxs("div",{className:"text-xl sm:text-2xl font-bold font-mono text-amber-300",children:[n.pending," Trade"]}),r.jsx("span",{className:"text-[10px] text-amber-300/80",children:"Menunggu konfirmasi Anda"})]})]}),o.length>0?r.jsxs("div",{className:"p-4 rounded-2xl bg-gradient-to-r from-purple-950/40 via-bg-card to-purple-950/20 border border-purple-500/30 shadow-md space-y-2.5",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(wt,{size:16,className:"text-purple-400"}),r.jsxs("span",{className:"text-xs font-bold text-purple-200 font-mono",children:["Aturan Pengaman Emas Damian (Batch #",o[0].batch_index,")"]}),r.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40",children:"Aktif pada Analisa Damian"})]}),r.jsxs("span",{className:"text-[10px] text-text-muted font-mono hidden sm:inline",children:["Model Auditor: ",o[0].model_used]})]}),r.jsx("div",{className:"p-3 rounded-xl bg-bg-elevated/40 border border-border/80",children:r.jsx(Ya,{content:o[0].audit_summary})}),r.jsxs("p",{className:"text-[10px] text-purple-300 flex items-center gap-1",children:[r.jsx(Fe,{size:11,className:"text-purple-400"}),"Aturan ini otomatis disuntikkan ke otak Damian setiap kali Anda meminta analisa baru agar tidak mengulangi kesalahan sebelumnya."]})]}):r.jsx("div",{className:"p-3.5 rounded-xl bg-purple-500/10 border border-purple-500/20 text-xs text-purple-200 flex items-center justify-between gap-3",children:r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.jsx(wt,{size:16,className:"text-purple-400 shrink-0"}),r.jsxs("span",{children:[r.jsx("strong",{children:"Siklus Pembelajaran Mandiri:"})," Kumpulkan 10 trade yang terkena Stop Loss di bawah ini, lalu jalankan ",r.jsx("strong",{children:"Audit Memori Damian"})," untuk merumuskan aturan pengaman baru secara otomatis!"]})]})}),r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2.5 pt-2",children:[r.jsx("div",{className:"flex items-center gap-1 overflow-x-auto no-scrollbar",children:[{id:"ALL",label:`Semua (${n.total})`},{id:"PENDING",label:`Pending (${n.pending})`},{id:"HIT_TP",label:`Hit TP (${n.hit_tp})`},{id:"HIT_SL",label:`Hit SL (${n.hit_sl})`},{id:"CANCELLED",label:`Batal (${n.cancelled})`}].map(N=>r.jsx("button",{type:"button",onClick:()=>u(N.id),className:`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all shrink-0 ${h===N.id?"bg-purple-600 text-white shadow-sm":"bg-bg-elevated/70 text-text-secondary hover:text-text-primary"}`,children:N.label},N.id))}),r.jsxs("div",{className:"relative w-full sm:w-60",children:[r.jsx(Zs,{size:13,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-text-muted"}),r.jsx("input",{type:"text",value:m,onChange:N=>x(N.target.value),placeholder:"Cari pair (e.g. BTC, SOL)...",className:"w-full bg-bg-elevated border border-border rounded-lg pl-8 pr-2.5 py-1.5 text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500/50"})]})]}),c?r.jsxs("div",{className:"py-12 flex flex-col items-center justify-center space-y-2 text-text-muted",children:[r.jsx(Pe,{size:24,className:"animate-spin text-purple-400"}),r.jsx("p",{className:"text-xs",children:"Memuat data Jurnal Trade..."})]}):Y.length===0?r.jsxs("div",{className:"py-12 border border-dashed border-border rounded-2xl flex flex-col items-center justify-center text-center p-6 space-y-2",children:[r.jsx(Pr,{size:32,className:"text-text-muted"}),r.jsx("p",{className:"text-sm font-bold text-text-primary",children:"Belum Ada Catatan Trade"}),r.jsxs("p",{className:"text-xs text-text-muted max-w-sm",children:["Gunakan Damian untuk menganalisa koin, lalu klik tombol ",r.jsx("strong",{children:'"📌 Catat ke Jurnal"'})," pada Card Kesimpulan untuk memantau performanya di sini."]})]}):r.jsx("div",{className:"space-y-3",children:Y.map(N=>r.jsxs("div",{className:"p-4 rounded-xl bg-bg-card border border-border hover:border-border-hover transition-all space-y-3 shadow-sm group",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pb-2.5 border-b border-border/50",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("span",{className:"text-sm font-bold font-mono text-text-primary",children:N.symbol}),r.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-mono font-bold border ${N.bias.includes("LONG")||N.bias.includes("BUY")?"bg-emerald-500/15 text-emerald-300 border-emerald-500/30":N.bias.includes("SHORT")||N.bias.includes("SELL")?"bg-rose-500/15 text-rose-300 border-rose-500/30":"bg-amber-500/15 text-amber-300 border-amber-500/30"}`,children:N.bias}),we(N.status),N.failure_tag&&r.jsxs("span",{className:"px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-rose-950/60 border border-rose-500/40 text-rose-300 flex items-center gap-1",children:[N.failure_tag==="WICK_HUNT"&&"⚡ Jarum Wick Hunt",N.failure_tag==="FALSE_BREAKOUT"&&"🛑 False Breakout",N.failure_tag==="BTC_DUMP"&&"📉 Market / BTC Drag",N.failure_tag==="TREND_REVERSAL"&&"🔄 Trend Reversal",N.failure_tag==="PREMATURE_ENTRY"&&"⚠️ Entry Prematur",N.failure_tag==="OTHER"&&"📝 Alasan Lainnya",!["WICK_HUNT","FALSE_BREAKOUT","BTC_DUMP","TREND_REVERSAL","PREMATURE_ENTRY","OTHER"].includes(N.failure_tag)&&N.failure_tag]}),N.holding_duration_seconds!=null&&N.holding_duration_seconds>0&&r.jsxs("span",{className:"text-[10px] font-mono text-purple-300/90 flex items-center gap-1 bg-purple-500/10 px-1.5 py-0.5 rounded border border-purple-500/20",children:[r.jsx(Fs,{size:10,className:"text-purple-400"}),Math.floor(N.holding_duration_seconds/3600)>0?`${Math.floor(N.holding_duration_seconds/3600)}j ${Math.floor(N.holding_duration_seconds%3600/60)}m`:`${Math.floor(N.holding_duration_seconds/60)}m`]}),N.exit_price!=null&&N.exit_price>0&&r.jsxs("span",{className:"text-[10px] font-mono text-emerald-300/90 bg-emerald-500/10 px-1.5 py-0.5 rounded border border-emerald-500/20",children:["Exit: $",N.exit_price>=1e3?N.exit_price.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):N.exit_price>=1?N.exit_price.toFixed(4):N.exit_price>=.01?N.exit_price.toFixed(6):N.exit_price.toFixed(8)]}),N.audited&&r.jsx("span",{className:"text-[9px] font-mono px-1.5 py-0.2 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30",children:"Diaudit"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-[10px] text-text-muted font-mono",children:new Date(N.created_at).toLocaleString("id-ID",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"})}),s&&r.jsx("button",{type:"button",onClick:()=>s(N.symbol),className:"p-1 rounded text-text-muted hover:text-purple-300 transition-colors",title:"Buka pair ini di Damian",children:r.jsx(Be,{size:13})}),r.jsx("button",{type:"button",onClick:()=>Se(N),className:"p-1 rounded text-text-muted hover:text-rose-400 transition-colors",title:"Hapus dari jurnal",children:r.jsx(Qt,{size:13})})]})]}),r.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs font-mono",children:[r.jsxs("div",{className:"p-2 rounded-lg bg-bg-elevated/70 border border-border",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"ENTRY ZONE"}),r.jsx("span",{className:"text-text-primary font-bold",children:N.entry_zone||"N/A"})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-rose-500/10 border border-rose-500/20",children:[r.jsx("span",{className:"text-[9px] text-rose-300 block",children:"STOP LOSS"}),r.jsx("span",{className:"text-rose-400 font-bold",children:N.stop_loss||"N/A"})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-emerald-500/10 border border-emerald-500/20",children:[r.jsx("span",{className:"text-[9px] text-emerald-300 block",children:"TARGET TP"}),r.jsx("span",{className:"text-emerald-400 font-bold",children:N.take_profit||"N/A"})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-purple-500/10 border border-purple-500/20",children:[r.jsx("span",{className:"text-[9px] text-purple-300 block",children:"R:R & LEV"}),r.jsxs("span",{className:"text-purple-300 font-bold",children:[N.risk_reward||"1:2"," • ",N.leverage||"2-3x"]})]})]}),N.summary_tldr&&r.jsxs("p",{className:"text-xs text-text-secondary leading-relaxed bg-bg-elevated/40 p-2.5 rounded-lg border border-border/60",children:[r.jsx("span",{className:"font-semibold text-text-primary",children:"💡 Intisari: "}),N.summary_tldr]}),N.outcome_note&&r.jsxs("p",{className:"text-[11px] text-text-muted italic bg-bg-elevated/60 px-2.5 py-1.5 rounded border border-border/80",children:["📝 Catatan Hasil: ",N.outcome_note]}),N.snapshot_data&&r.jsxs("div",{className:"pt-1",children:[r.jsxs("button",{type:"button",onClick:()=>le(N.id),className:"w-full flex items-center justify-between px-3 py-2 rounded-lg bg-purple-950/20 hover:bg-purple-950/40 border border-purple-500/20 hover:border-purple-500/40 text-xs font-mono text-purple-300 transition-all shadow-sm",children:[r.jsxs("span",{className:"flex items-center gap-1.5 font-bold",children:[r.jsx(ei,{size:13,className:"text-purple-400"}),r.jsx("span",{children:"Data Pasar Saat Rekomendasi (Telemetri Kuantitatif)"})]}),r.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-text-muted",children:[T[N.id]?"Sembunyikan":"Buka Sidik Jari Pasar",T[N.id]?r.jsx(Us,{size:13}):r.jsx(_t,{size:13})]})]}),T[N.id]&&r.jsxs("div",{className:"mt-2 p-3.5 rounded-xl bg-bg-elevated/70 border border-purple-500/20 space-y-3 animate-fade-in text-xs font-mono",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 pb-2",children:[r.jsxs("span",{className:"text-[10px] uppercase font-bold tracking-wider text-purple-300 flex items-center gap-1",children:[r.jsx(ot,{size:12,className:"text-purple-400"}),"Sidik Jari Pasar Mikrostruktur Pada Saat Entry"]}),r.jsxs("span",{className:"text-[10px] text-text-muted",children:["Model: ",N.model_used||"Damian Quant Engine"]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2 text-[11px]",children:[r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"MARK PRICE & 24H POS"}),r.jsx("div",{className:"font-bold text-text-primary",children:N.snapshot_data.mark_price_str||(N.snapshot_data.mark_price?`$${N.snapshot_data.mark_price}`:"N/A")}),r.jsxs("div",{className:"text-[10px] text-purple-300",children:["Posisi: ",N.snapshot_data.range_position_pct??"50","% (",N.snapshot_data.range_zone_label||"Equilibrium",")"]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"ORDER FLOW CVD"}),r.jsx("div",{className:"font-bold text-text-primary",children:N.snapshot_data.cvd_verdict||"Netral"}),r.jsxs("div",{className:"text-[10px] text-text-secondary truncate",children:["Spot: ",N.snapshot_data.spot_cvd||"0"," | Fut: ",N.snapshot_data.futures_cvd||"0"]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"FUNDING RATE 8H & APR"}),r.jsxs("div",{className:`font-bold ${(N.snapshot_data.avg_fr_8h_pct||0)<0?"text-emerald-400":"text-rose-400"}`,children:[N.snapshot_data.avg_fr_8h_pct!=null?`${Number(N.snapshot_data.avg_fr_8h_pct).toFixed(4)}%`:"N/A"," ",r.jsxs("span",{className:"text-[9px] font-normal text-text-muted",children:["(",N.snapshot_data.annualized_apr_pct!=null?`${Number(N.snapshot_data.annualized_apr_pct).toFixed(2)}% APR`:"",")"]})]}),r.jsxs("div",{className:"text-[10px] text-text-muted",children:["Settlement: ",N.snapshot_data.funding_countdown||"N/A"]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"ORDERBOOK SKEW (TOP 20)"}),r.jsxs("div",{className:"font-bold text-text-primary",children:[N.snapshot_data.resting_pressure||"Neutral"," ",r.jsxs("span",{className:"text-[9px] font-normal text-text-muted",children:["(",N.snapshot_data.depth_ratio?`${N.snapshot_data.depth_ratio}x`:"1.0x",")"]})]}),r.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:["Bids $",Number(N.snapshot_data.bid_depth_usd||0).toLocaleString()," vs Asks $",Number(N.snapshot_data.ask_depth_usd||0).toLocaleString()]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"STRUKTUR MULTI-TIMEFRAME"}),r.jsx("div",{className:"flex items-center gap-1 flex-wrap pt-0.5",children:["15m","1h","4h","1d"].map(Q=>{const J=N.snapshot_data?.market_structure?.[Q]||"neutral",ee=J.toLowerCase().includes("bull")||J.toLowerCase().includes("uptrend"),W=J.toLowerCase().includes("bear")||J.toLowerCase().includes("downtrend");return r.jsxs("span",{className:`px-1 py-0.2 rounded text-[9px] font-bold ${ee?"bg-emerald-500/20 text-emerald-300":W?"bg-rose-500/20 text-rose-300":"bg-gray-500/20 text-gray-300"}`,children:[Q.toUpperCase(),":",J.substring(0,4).toUpperCase()]},Q)})})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"SQUEEZE & BREAKOUT RADAR"}),r.jsxs("div",{className:"font-bold text-purple-300",children:[N.snapshot_data.squeeze_intensity||"NORMAL"," ",r.jsxs("span",{className:"text-[9px] font-normal text-text-muted",children:["(",N.snapshot_data.compression_ratio?`CR: ${N.snapshot_data.compression_ratio}`:"",")"]})]}),r.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:["Radar: ",N.snapshot_data.breakout_radar?.radar_label||"NORMAL"]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"WHALES & LEAD-LAG"}),r.jsxs("div",{className:"font-bold text-text-primary",children:["Taker Buy: ",N.snapshot_data.taker_buy_pct??50,"%"]}),r.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:["Pemimpin: ",N.snapshot_data.leading_exchange||"N/A"," ",N.snapshot_data.lead_lag_spread_bps?`(+${N.snapshot_data.lead_lag_spread_bps} bps)`:""]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"KEYAKINAN & REZIM PASAR"}),r.jsxs("div",{className:"font-bold text-purple-200",children:["Conviction: ",N.snapshot_data.conviction??"N/A","/10"," ",r.jsxs("span",{className:"text-[9px] font-normal text-text-muted",children:["(",N.snapshot_data.confluence_pct??"N/A","%)"]})]}),r.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:["Rezim: ",N.snapshot_data.global_regime||"NEUTRAL"]})]})]}),N.invalidation&&r.jsxs("div",{className:"p-2 rounded-lg bg-rose-500/10 border border-rose-500/20 text-[10px] text-rose-200 flex items-start gap-1.5",children:[r.jsx(Rt,{size:12,className:"text-rose-400 shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("strong",{className:"text-rose-300",children:"Syarat Pembatalan (Invalidation Rule):"})," ",N.invalidation]})]}),N.snapshot_data.warnings&&N.snapshot_data.warnings.length>0&&r.jsxs("div",{className:"p-2 rounded-lg bg-amber-500/10 border border-amber-500/20 text-[10px] text-amber-200 flex items-start gap-1.5",children:[r.jsx(ve,{size:12,className:"text-amber-400 shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("strong",{className:"text-amber-300",children:"Peringatan Terdeteksi Saat Entry:"})," ",N.snapshot_data.warnings.join(" • ")]})]})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-2 border-t border-border/50",children:[r.jsx("span",{className:"text-[11px] text-text-muted font-medium",children:N.status==="PENDING"?"Konfirmasi hasil trade Anda di bursa:":r.jsxs("span",{children:["Status: ",r.jsx("strong",{className:"text-text-primary",children:N.status==="HIT_TP"?"🟢 Selesai Hit TP":N.status==="HIT_SL"?"🔴 Selesai Hit SL":"⚪ Sinyal Batal / BE"})," ",r.jsx("span",{className:"text-text-muted text-[10px]",children:"(klik untuk ubah):"})]})}),r.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>K(N,"HIT_TP"),className:`text-xs py-1 px-2.5 transition-all ${N.status==="HIT_TP"?"bg-emerald-500/30 text-emerald-200 border-emerald-500 font-bold shadow-sm shadow-emerald-950/40":"bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-300 border border-emerald-500/30"}`,icon:r.jsx(at,{size:12}),children:"Hit TP"}),r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>K(N,"HIT_SL"),className:`text-xs py-1 px-2.5 transition-all ${N.status==="HIT_SL"?"bg-rose-500/30 text-rose-200 border-rose-500 font-bold shadow-sm shadow-rose-950/40":"bg-rose-500/10 hover:bg-rose-500/20 text-rose-300 border border-rose-500/30"}`,icon:r.jsx(Et,{size:12}),children:"Hit SL"}),r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>K(N,"CANCELLED"),className:`text-xs py-1 px-2.5 transition-all ${N.status==="CANCELLED"?"bg-gray-500/30 text-gray-200 border-gray-400 font-bold shadow-sm":"bg-gray-500/10 hover:bg-gray-500/20 text-gray-300 border border-gray-500/30"}`,children:"Batal"}),N.status!=="PENDING"&&r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>be(N),className:"bg-amber-500/15 hover:bg-amber-500/25 text-amber-300 border border-amber-500/30 text-xs py-1 px-2 transition-all",title:"Kembalikan ke status Sedang Berjalan (Pending)",children:"Reset ke Pending"})]})]})]},N.id))})]}),b&&r.jsx(Is,{isOpen:!!b,onClose:()=>f(null),title:`Konfirmasi Hasil Trade: ${b.entry.symbol}`,size:b.targetStatus==="HIT_SL"?"md":"sm",children:r.jsxs("div",{className:"space-y-3.5",children:[r.jsxs("div",{className:"p-3 rounded-lg bg-bg-elevated border border-border text-xs space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-text-muted",children:"Pair & Bias:"}),r.jsxs("span",{className:"font-bold text-text-primary",children:[b.entry.symbol," (",b.entry.bias,")"]})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-text-muted",children:"Target Status:"}),r.jsx("span",{className:`font-bold ${b.targetStatus==="HIT_TP"?"text-emerald-400":b.targetStatus==="HIT_SL"?"text-rose-400":"text-gray-400"}`,children:b.targetStatus})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-text-muted",children:"Durasi Posisi Bertahan:"}),r.jsxs("span",{className:"font-bold font-mono text-purple-300 flex items-center gap-1",children:[r.jsx(Fs,{size:11,className:"text-purple-400"}),F(b.entry.created_at).formatted]})]})]}),b.targetStatus==="HIT_SL"&&r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"block text-xs font-semibold text-rose-300",children:"⚡ Diagnosis Penyebab Stop Loss (Wajib untuk Pembelajaran Damian):"}),r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-1.5",children:iu.map(N=>r.jsxs("button",{type:"button",onClick:()=>S(N.id),className:`p-2 rounded-lg text-left border transition-all ${v===N.id?"bg-rose-500/20 border-rose-500 text-rose-200 font-bold shadow-sm":"bg-bg-elevated/60 border-border/80 text-text-secondary hover:text-text-primary hover:border-border-hover"}`,children:[r.jsx("span",{className:"block font-mono text-[11px] font-bold",children:N.label}),r.jsx("span",{className:"text-[9px] text-text-muted block mt-0.5 line-clamp-1",children:N.desc})]},N.id))})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-xs font-semibold text-text-secondary mb-1",children:["Harga Exit (",b.targetStatus==="HIT_SL"?"SL Hit":"TP Hit",") — Opsional"]}),r.jsx("input",{type:"number",step:"any",value:j,onChange:N=>k(N.target.value),placeholder:b.targetStatus==="HIT_SL"?"e.g. 0.0868":"e.g. 0.1026",className:"w-full px-2.5 py-1.5 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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs font-semibold text-text-secondary mb-1",children:"Level Invalidation Terpasang"}),r.jsx("div",{className:"px-2.5 py-1.5 rounded-lg bg-bg-elevated/50 border border-border text-xs text-text-muted font-mono truncate h-[34px] flex items-center",children:b.entry.stop_loss||"N/A"})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs font-semibold text-text-secondary mb-1",children:"Catatan Evaluasi Pribadi / Catatan Post-Mortem (Opsional)"}),r.jsx("textarea",{value:g,onChange:N=>p(N.target.value),placeholder:"Contoh: Kena wick hunt pas settlement bursa jam 19:00, candle 1H langsung mantul kembali ke atas...",rows:2,className:"w-full p-2.5 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500"})]}),r.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2 border-t border-border",children:[r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>f(null),disabled:C,children:"Batal"}),r.jsx(se,{variant:"primary",size:"sm",onClick:te,loading:C,className:`${b.targetStatus==="HIT_TP"?"bg-emerald-600 hover:bg-emerald-500 text-white":b.targetStatus==="HIT_SL"?"bg-rose-600 hover:bg-rose-500 text-white":"bg-purple-600 hover:bg-purple-500 text-white"}`,children:"Konfirmasi Simpan"})]})]})}),$&&r.jsx(Is,{isOpen:$,onClose:()=>z(!1),title:"Audit Memori Pembelajaran Damian",size:"md",children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"p-3 rounded-xl bg-purple-500/10 border border-purple-500/20 text-xs text-purple-200 flex items-start gap-2.5",children:[r.jsx(wt,{size:18,className:"text-purple-400 shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("span",{className:"font-bold text-purple-100 block mb-0.5",children:"Root Cause Analysis (RCA) 10 Trade Gagal"}),"Damian akan menganalisa persamaan kondisi pasar pada trade yang terkena Stop Loss dan menyusun 3–4 Aturan Pengaman Emas agar tidak terjebak di pola yang sama pada analisa selanjutnya."]})]}),r.jsxs("div",{className:"p-3 rounded-xl bg-bg-elevated border border-border text-xs space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-text-muted",children:"Trade Stop Loss Tersedia:"}),r.jsxs("span",{className:"font-bold font-mono text-rose-400",children:[n.unaudited_sl_count," Trade"]})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-text-muted",children:"Target Audit Batch:"}),r.jsx("span",{className:"font-bold font-mono text-purple-300",children:"Maksimal 10 Trade per Batch"})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-1",children:[r.jsx("label",{className:"text-xs font-semibold text-text-secondary",children:"Model AI untuk Audit"}),r.jsxs("span",{className:"text-[10px] font-mono px-2 py-0.5 rounded bg-purple-500/15 border border-purple-500/30 text-purple-300 font-bold uppercase",children:["Provider: ",A.provider]})]}),r.jsx("select",{value:V,onChange:N=>q(N.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:_.map(N=>r.jsxs("option",{value:N.id,children:[N.label," (",N.id,")"]},N.id))})]}),r.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2 border-t border-border",children:[r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>z(!1),disabled:Z,children:"Tutup"}),r.jsx(se,{variant:"primary",size:"sm",onClick:ge,loading:Z,disabled:n.unaudited_sl_count===0,icon:r.jsx(wt,{size:13}),className:"bg-purple-600 hover:bg-purple-500 text-white",children:Z?"Menganalisa Pola Kesalahan...":"Sintesis Golden Rules Sekarang"})]})]})}),O&&r.jsx(Is,{isOpen:!!O,onClose:()=>!R&&M(null),title:`Hapus Trade: ${O.symbol}`,size:"sm",children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"p-3.5 rounded-xl bg-rose-500/10 border border-rose-500/25 text-xs text-rose-200 flex items-start gap-3",children:[r.jsx("div",{className:"p-2 rounded-lg bg-rose-500/20 text-rose-400 shrink-0",children:r.jsx(Qt,{size:18})}),r.jsxs("div",{className:"space-y-1",children:[r.jsx("span",{className:"font-bold text-rose-100 block text-sm",children:"Konfirmasi Hapus Permanen"}),r.jsxs("p",{className:"text-rose-200/90 leading-relaxed",children:["Apakah Anda yakin ingin menghapus catatan trade ",r.jsx("strong",{children:O.symbol})," (",O.bias,")?"]}),r.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:["⚠️ Data ini akan ",r.jsx("strong",{children:"dihapus permanen dari database"})," dan statistik Win Rate akan langsung dikalkulasi ulang."]})]})]}),r.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2 border-t border-border",children:[r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>M(null),disabled:R,children:"Batal"}),r.jsx(se,{variant:"primary",size:"sm",onClick:tt,loading:R,className:"bg-rose-600 hover:bg-rose-500 text-white border border-rose-500/40",icon:r.jsx(Qt,{size:13}),children:"Ya, Hapus dari Database"})]})]})})]})}const Zi={getCandles:async(s,e="15m",t=150,i)=>{const n={timeframe:e,limit:t};return i&&i!=="auto"&&(n.exchange=i),(await ie.get(`/api/market/${s}/candles`,{params:n})).data},getMultiStream:async s=>(await ie.get(`/api/market/${s}/multi-stream`)).data,getFundingHistory:async(s,e=30)=>(await ie.get(`/api/market/${s}/funding-history`,{params:{limit:e}})).data};function nu({symbol:s,timeframe:e,exchange:t="auto",enabled:i=!0}){const[n,a]=y.useState([]),[o,l]=y.useState(0),[c,d]=y.useState(null),[h,u]=y.useState(!1),m=y.useRef(null),x=y.useRef(null),b=y.useRef(!0);y.useEffect(()=>{a([]),l(0)},[s,e,t]),y.useEffect(()=>{d(null)},[s]);const{data:f,isLoading:g,refetch:p,error:v}=Zt({queryKey:["chartCandles",s,e,t],queryFn:()=>Zi.getCandles(s,e,180,t),enabled:i&&!!s,staleTime:1e4,gcTime:6e4,refetchInterval:h?!1:5e3});y.useEffect(()=>{if(f?.candles){const k=(f.symbol||"").toUpperCase().replace(/[/-]/g,""),C=(s||"").toUpperCase().replace(/[/-]/g,"");(!k||k===C)&&(a(f.candles),f.current_price&&f.current_price>0&&l(f.current_price))}},[f,s]);const{data:S}=Zt({queryKey:["multiStream",s],queryFn:()=>Zi.getMultiStream(s),enabled:i&&!!s,refetchInterval:h?1e4:3e3});y.useEffect(()=>{S&&S.symbol===s&&(d(S),S.ref_price&&l(k=>k>0?k:S.ref_price||0))},[S,s]);const j=y.useCallback(()=>{if(!i||!s)return;const k=wd(s);if(k)try{m.current&&(m.current.onclose=null,m.current.close());const C=new WebSocket(k);m.current=C,C.onopen=()=>{u(!0)},C.onmessage=E=>{try{const T=JSON.parse(E.data);if(T.type==="chart_tick"){const D=(T.symbol||"").toUpperCase().replace(/[/-]/g,""),O=(s||"").toUpperCase().replace(/[/-]/g,"");if(D&&O&&D!==O)return;const M=Number(T.price);if(!M||isNaN(M)||M<=0)return;l(M),a(R=>{if(!R||R.length===0)return R;const L={...R[R.length-1]};if(L.close>0){const q=M/L.close;if(q<.2||q>5)return R}const $=T.time||Math.floor(Date.now()/1e3);let z=900;e==="1m"?z=60:e==="3m"?z=180:e==="5m"?z=300:e==="30m"?z=1800:e==="1h"?z=3600:e==="2h"?z=7200:e==="4h"?z=14400:e==="1d"&&(z=86400);const V=Math.floor($/z)*z;if(L.time>=V)return L.close=M,L.high=Math.max(L.high,M),L.low=Math.min(L.low,M),[...R.slice(0,-1),L];{const q={time:V,open:M,high:M,low:M,close:M,volume:0,delta:0,cvd:L.cvd||0,open_interest:L.open_interest??null};return[...R,q]}})}T.exchanges&&d(D=>{if(!D)return D;const O=typeof T.price=="number"&&Number.isFinite(T.price)&&T.price>0?T.price:D.ref_price,M={...D.exchanges},R=L=>{const $=T.exchanges?.[L];typeof $=="number"&&Number.isFinite($)&&$>0&&M[L]&&(M[L]={...M[L],available:!0,mark_price:$,diff_pct:O>0?Number((($-O)/O*100).toFixed(3)):M[L].diff_pct})};return R("binance"),R("bybit"),R("okx"),R("bitget"),{...D,ref_price:O,timestamp:typeof T.time=="number"?T.time:D.timestamp,exchanges:M}})}catch{}},C.onclose=()=>{u(!1),b.current&&(x.current=setTimeout(()=>{b.current&&j()},3e3))},C.onerror=()=>{u(!1)}}catch{u(!1)}},[i,s,e]);return y.useEffect(()=>{b.current=!0,j();const k=()=>{x.current&&(clearTimeout(x.current),x.current=null),m.current&&(m.current.onclose=null,m.current.close(),m.current=null),u(!1),b.current&&j()};return window.addEventListener("perps_server_url_changed",k),()=>{window.removeEventListener("perps_server_url_changed",k),b.current=!1,x.current&&clearTimeout(x.current),m.current&&(m.current.onclose=null,m.current.close(),m.current=null)}},[j]),{candles:n,currentPrice:o,multiStream:c,isAggregated:f?.is_aggregated??!1,exchangesIncluded:f?.exchanges_included??["binance"],summary:f?.summary,isLoading:g,isWsConnected:h,refetchCandles:p,error:v?v.message:null}}function re(s){var e=s.width,t=s.height;if(e<0)throw new Error("Negative width is not allowed for Size");if(t<0)throw new Error("Negative height is not allowed for Size");return{width:e,height:t}}function nt(s,e){return s.width===e.width&&s.height===e.height}var au=function(){function s(e){var t=this;this._resolutionListener=function(){return t._onResolutionChanged()},this._resolutionMediaQueryList=null,this._observers=[],this._window=e,this._installResolutionListener()}return s.prototype.dispose=function(){this._uninstallResolutionListener(),this._window=null},Object.defineProperty(s.prototype,"value",{get:function(){return this._window.devicePixelRatio},enumerable:!1,configurable:!0}),s.prototype.subscribe=function(e){var t=this,i={next:e};return this._observers.push(i),{unsubscribe:function(){t._observers=t._observers.filter(function(n){return n!==i})}}},s.prototype._installResolutionListener=function(){if(this._resolutionMediaQueryList!==null)throw new Error("Resolution listener is already installed");var e=this._window.devicePixelRatio;this._resolutionMediaQueryList=this._window.matchMedia("all and (resolution: ".concat(e,"dppx)")),this._resolutionMediaQueryList.addListener(this._resolutionListener)},s.prototype._uninstallResolutionListener=function(){this._resolutionMediaQueryList!==null&&(this._resolutionMediaQueryList.removeListener(this._resolutionListener),this._resolutionMediaQueryList=null)},s.prototype._reinstallResolutionListener=function(){this._uninstallResolutionListener(),this._installResolutionListener()},s.prototype._onResolutionChanged=function(){var e=this;this._observers.forEach(function(t){return t.next(e._window.devicePixelRatio)}),this._reinstallResolutionListener()},s}();function ou(s){return new au(s)}var lu=function(){function s(e,t,i){var n;this._canvasElement=null,this._bitmapSizeChangedListeners=[],this._suggestedBitmapSize=null,this._suggestedBitmapSizeChangedListeners=[],this._devicePixelRatioObservable=null,this._canvasElementResizeObserver=null,this._canvasElement=e,this._canvasElementClientSize=re({width:this._canvasElement.clientWidth,height:this._canvasElement.clientHeight}),this._transformBitmapSize=t??function(a){return a},this._allowResizeObserver=(n=i?.allowResizeObserver)!==null&&n!==void 0?n:!0,this._chooseAndInitObserver()}return s.prototype.dispose=function(){var e,t;if(this._canvasElement===null)throw new Error("Object is disposed");(e=this._canvasElementResizeObserver)===null||e===void 0||e.disconnect(),this._canvasElementResizeObserver=null,(t=this._devicePixelRatioObservable)===null||t===void 0||t.dispose(),this._devicePixelRatioObservable=null,this._suggestedBitmapSizeChangedListeners.length=0,this._bitmapSizeChangedListeners.length=0,this._canvasElement=null},Object.defineProperty(s.prototype,"canvasElement",{get:function(){if(this._canvasElement===null)throw new Error("Object is disposed");return this._canvasElement},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"canvasElementClientSize",{get:function(){return this._canvasElementClientSize},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"bitmapSize",{get:function(){return re({width:this.canvasElement.width,height:this.canvasElement.height})},enumerable:!1,configurable:!0}),s.prototype.resizeCanvasElement=function(e){this._canvasElementClientSize=re(e),this.canvasElement.style.width="".concat(this._canvasElementClientSize.width,"px"),this.canvasElement.style.height="".concat(this._canvasElementClientSize.height,"px"),this._invalidateBitmapSize()},s.prototype.subscribeBitmapSizeChanged=function(e){this._bitmapSizeChangedListeners.push(e)},s.prototype.unsubscribeBitmapSizeChanged=function(e){this._bitmapSizeChangedListeners=this._bitmapSizeChangedListeners.filter(function(t){return t!==e})},Object.defineProperty(s.prototype,"suggestedBitmapSize",{get:function(){return this._suggestedBitmapSize},enumerable:!1,configurable:!0}),s.prototype.subscribeSuggestedBitmapSizeChanged=function(e){this._suggestedBitmapSizeChangedListeners.push(e)},s.prototype.unsubscribeSuggestedBitmapSizeChanged=function(e){this._suggestedBitmapSizeChangedListeners=this._suggestedBitmapSizeChangedListeners.filter(function(t){return t!==e})},s.prototype.applySuggestedBitmapSize=function(){if(this._suggestedBitmapSize!==null){var e=this._suggestedBitmapSize;this._suggestedBitmapSize=null,this._resizeBitmap(e),this._emitSuggestedBitmapSizeChanged(e,this._suggestedBitmapSize)}},s.prototype._resizeBitmap=function(e){var t=this.bitmapSize;nt(t,e)||(this.canvasElement.width=e.width,this.canvasElement.height=e.height,this._emitBitmapSizeChanged(t,e))},s.prototype._emitBitmapSizeChanged=function(e,t){var i=this;this._bitmapSizeChangedListeners.forEach(function(n){return n.call(i,e,t)})},s.prototype._suggestNewBitmapSize=function(e){var t=this._suggestedBitmapSize,i=re(this._transformBitmapSize(e,this._canvasElementClientSize)),n=nt(this.bitmapSize,i)?null:i;t===null&&n===null||t!==null&&n!==null&&nt(t,n)||(this._suggestedBitmapSize=n,this._emitSuggestedBitmapSizeChanged(t,n))},s.prototype._emitSuggestedBitmapSizeChanged=function(e,t){var i=this;this._suggestedBitmapSizeChangedListeners.forEach(function(n){return n.call(i,e,t)})},s.prototype._chooseAndInitObserver=function(){var e=this;if(!this._allowResizeObserver){this._initDevicePixelRatioObservable();return}du().then(function(t){return t?e._initResizeObserver():e._initDevicePixelRatioObservable()})},s.prototype._initDevicePixelRatioObservable=function(){var e=this;if(this._canvasElement!==null){var t=cn(this._canvasElement);if(t===null)throw new Error("No window is associated with the canvas");this._devicePixelRatioObservable=ou(t),this._devicePixelRatioObservable.subscribe(function(){return e._invalidateBitmapSize()}),this._invalidateBitmapSize()}},s.prototype._invalidateBitmapSize=function(){var e,t;if(this._canvasElement!==null){var i=cn(this._canvasElement);if(i!==null){var n=(t=(e=this._devicePixelRatioObservable)===null||e===void 0?void 0:e.value)!==null&&t!==void 0?t:i.devicePixelRatio,a=this._canvasElement.getClientRects(),o=a[0]!==void 0?hu(a[0],n):re({width:this._canvasElementClientSize.width*n,height:this._canvasElementClientSize.height*n});this._suggestNewBitmapSize(o)}}},s.prototype._initResizeObserver=function(){var e=this;this._canvasElement!==null&&(this._canvasElementResizeObserver=new ResizeObserver(function(t){var i=t.find(function(o){return o.target===e._canvasElement});if(!(!i||!i.devicePixelContentBoxSize||!i.devicePixelContentBoxSize[0])){var n=i.devicePixelContentBoxSize[0],a=re({width:n.inlineSize,height:n.blockSize});e._suggestNewBitmapSize(a)}}),this._canvasElementResizeObserver.observe(this._canvasElement,{box:"device-pixel-content-box"}))},s}();function cu(s,e){return new lu(s,e.transform,e.options)}function cn(s){return s.ownerDocument.defaultView}function du(){return new Promise(function(s){var e=new ResizeObserver(function(t){s(t.every(function(i){return"devicePixelContentBoxSize"in i})),e.disconnect()});e.observe(document.body,{box:"device-pixel-content-box"})}).catch(function(){return!1})}function hu(s,e){return re({width:Math.round(s.left*e+s.width*e)-Math.round(s.left*e),height:Math.round(s.top*e+s.height*e)-Math.round(s.top*e)})}var uu=function(){function s(e,t,i){if(t.width===0||t.height===0)throw new TypeError("Rendering target could only be created on a media with positive width and height");if(this._mediaSize=t,i.width===0||i.height===0)throw new TypeError("Rendering target could only be created using a bitmap with positive integer width and height");this._bitmapSize=i,this._context=e}return s.prototype.useMediaCoordinateSpace=function(e){try{return this._context.save(),this._context.setTransform(1,0,0,1,0,0),this._context.scale(this._horizontalPixelRatio,this._verticalPixelRatio),e({context:this._context,mediaSize:this._mediaSize})}finally{this._context.restore()}},s.prototype.useBitmapCoordinateSpace=function(e){try{return this._context.save(),this._context.setTransform(1,0,0,1,0,0),e({context:this._context,mediaSize:this._mediaSize,bitmapSize:this._bitmapSize,horizontalPixelRatio:this._horizontalPixelRatio,verticalPixelRatio:this._verticalPixelRatio})}finally{this._context.restore()}},Object.defineProperty(s.prototype,"_horizontalPixelRatio",{get:function(){return this._bitmapSize.width/this._mediaSize.width},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"_verticalPixelRatio",{get:function(){return this._bitmapSize.height/this._mediaSize.height},enumerable:!1,configurable:!0}),s}();function ut(s,e){var t=s.canvasElementClientSize;if(t.width===0||t.height===0)return null;var i=s.bitmapSize;if(i.width===0||i.height===0)return null;var n=s.canvasElement.getContext("2d",e);return n===null?null:new uu(n,t,i)}/*! + * @license + * TradingView Lightweight Charts™ v5.2.1 + * Copyright (c) 2026 TradingView, Inc. + * Licensed under Apache License 2.0 https://www.apache.org/licenses/LICENSE-2.0 + */const Ja={title:"",visible:!0,hitTestTolerance:3,lastValueVisible:!0,priceLineVisible:!0,priceLineSource:0,priceLineWidth:1,priceLineColor:"",priceLineStyle:2,baseLineVisible:!0,baseLineWidth:1,baseLineColor:"#B2B5BE",baseLineStyle:0,priceFormat:{type:"price",precision:2,minMove:.01}};var dn,he;function et(s,e){const t=function(i,n){switch(i){case 0:default:return[];case 1:return[n,n];case 2:return[2*n,2*n];case 3:return[6*n,6*n];case 4:return[n,4*n]}}(e,s.lineWidth);return s.setLineDash(t),t}function Xa(s,e,t,i){s.beginPath();const n=s.lineWidth%2?.5:0;s.moveTo(t,e+n),s.lineTo(i,e+n),s.stroke()}function pe(s,e){if(!s)throw new Error("Assertion failed"+(e?": "+e:""))}function _e(s){if(s===void 0)throw new Error("Value is undefined");return s}function P(s){if(s===null)throw new Error("Value is null");return s}function Ye(s){return P(_e(s))}(function(s){s[s.Simple=0]="Simple",s[s.WithSteps=1]="WithSteps",s[s.Curved=2]="Curved"})(dn||(dn={})),function(s){s[s.Solid=0]="Solid",s[s.Dotted=1]="Dotted",s[s.Dashed=2]="Dashed",s[s.LargeDashed=3]="LargeDashed",s[s.SparseDotted=4]="SparseDotted"}(he||(he={}));class ce{constructor(){this.t=[]}i(e,t,i){const n={h:e,l:t,o:i===!0};this.t.push(n)}_(e){const t=this.t.findIndex(i=>e===i.h);t>-1&&this.t.splice(t,1)}u(e){this.t=this.t.filter(t=>t.l!==e)}p(e,t,i){const n=[...this.t];this.t=this.t.filter(a=>!a.o),n.forEach(a=>a.h(e,t,i))}v(){return this.t.length>0}m(){this.t=[]}}function Me(s,...e){for(const t of e)for(const i in t)t[i]!==void 0&&Object.prototype.hasOwnProperty.call(t,i)&&!["__proto__","constructor","prototype"].includes(i)&&(typeof t[i]!="object"||s[i]===void 0||Array.isArray(t[i])?s[i]=t[i]:Me(s[i],t[i]));return s}function Pt(s){return typeof s=="number"&&isFinite(s)}function rs(s){return typeof s=="number"&&s%1==0}function fs(s){return typeof s=="string"}function Ns(s){return typeof s=="boolean"}function $e(s){const e=s;if(!e||typeof e!="object")return e;let t,i,n;for(i in t=Array.isArray(e)?[]:{},e)e.hasOwnProperty(i)&&(n=e[i],t[i]=n&&typeof n=="object"?$e(n):n);return t}function hn(s){return s!==null}function ns(s){return s===null?void 0:s}const Za="-apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif";function Ks(s,e,t){return e===void 0&&(e=Za),`${t=t!==void 0?`${t} `:""}${s}px ${e}`}class mu{constructor(e){this.M={S:1,C:5,P:NaN,k:"",T:"",R:"",D:"",I:0,V:0,B:0,A:0,L:0},this.O=e}N(){const e=this.M,t=this.F(),i=this.W();return e.P===t&&e.T===i||(e.P=t,e.T=i,e.k=Ks(t,i),e.A=2.5/12*t,e.I=e.A,e.V=t/12*e.C,e.B=t/12*e.C,e.L=0),e.R=this.H(),e.D=this.U(),this.M}H(){return this.O.N().layout.textColor}U(){return this.O.$()}F(){return this.O.N().layout.fontSize}W(){return this.O.N().layout.fontFamily}}function Ti(s){return s<0?0:s>255?255:Math.round(s)||0}function un(s){return .199*s[0]+.687*s[1]+.114*s[2]}class pu{constructor(e,t){this.j=new Map,this.q=e,t&&(this.j=t)}Y(e,t){if(e==="transparent")return e;const i=this.K(e),n=i[3];return`rgba(${i[0]}, ${i[1]}, ${i[2]}, ${t*n})`}G(e){const t=this.K(e);return{Z:`rgb(${t[0]}, ${t[1]}, ${t[2]})`,X:un(t)>160?"black":"white"}}J(e){return un(this.K(e))}tt(e,t,i){const[n,a,o,l]=this.K(e),[c,d,h,u]=this.K(t),m=[Ti(n+i*(c-n)),Ti(a+i*(d-a)),Ti(o+i*(h-o)),(x=l+i*(u-l),x<=0||x>1?Math.min(Math.max(x,0),1):Math.round(1e4*x)/1e4)];var x;return`rgba(${m[0]}, ${m[1]}, ${m[2]}, ${m[3]})`}K(e){const t=this.j.get(e);if(t)return t;const i=function(o){const l=document.createElement("div");l.style.display="none",document.body.appendChild(l),l.style.color=o;const c=window.getComputedStyle(l).color;return document.body.removeChild(l),c}(e),n=i.match(/^rgba?\s*\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d*\.?\d+))?\)$/);if(!n){if(this.q.length)for(const o of this.q){const l=o(e);if(l)return this.j.set(e,l),l}throw new Error(`Failed to parse color: ${e}`)}const a=[parseInt(n[1],10),parseInt(n[2],10),parseInt(n[3],10),n[4]?parseFloat(n[4]):1];return this.j.set(e,a),a}}class fu{constructor(){this.it=[]}nt(e){this.it=e}st(e,t,i){this.it.forEach(n=>{n.st(e,t,i)})}}class Ue{st(e,t,i){e.useBitmapCoordinateSpace(n=>this.et(n,t,i))}}class xu extends Ue{constructor(){super(...arguments),this.rt=null}ht(e){this.rt=e}et({context:e,horizontalPixelRatio:t,verticalPixelRatio:i}){if(this.rt===null||this.rt.lt===null)return;const n=this.rt.lt,a=this.rt,o=Math.max(1,Math.floor(t))%2/2,l=c=>{e.beginPath();for(let d=n.to-1;d>=n.from;--d){const h=a.ot[d],u=Math.round(h._t*t)+o,m=h.ut*i,x=c*i+o;e.moveTo(u,m),e.arc(u,m,x,0,2*Math.PI)}e.fill()};a.ct>0&&(e.fillStyle=a.dt,l(a.ft+a.ct)),e.fillStyle=a.vt,l(a.ft)}}function bu(){return{ot:[{_t:0,ut:0,wt:0,Mt:0}],vt:"",dt:"",ft:0,ct:0,lt:null}}const gu={from:0,to:1};class vu{constructor(e,t,i){this.gt=new fu,this.bt=[],this.St=[],this.xt=!0,this.O=e,this.Ct=t,this.yt=i,this.gt.nt(this.bt)}Pt(e){this.kt(),this.xt=!0}Tt(){return this.xt&&(this.Rt(),this.xt=!1),this.gt}kt(){const e=this.yt.Dt();e.length!==this.bt.length&&(this.St=e.map(bu),this.bt=this.St.map(t=>{const i=new xu;return i.ht(t),i}),this.gt.nt(this.bt))}Rt(){const e=this.Ct.N().mode===2||!this.Ct.It(),t=this.yt.Vt(),i=this.Ct.Bt(),n=this.O.Et();this.kt(),t.forEach((a,o)=>{const l=this.St[o],c=a.At(i),d=a.Lt();!e&&c!==null&&a.It()&&d!==null?(l.vt=c.zt,l.ft=c.ft,l.ct=c.Ot,l.ot[0].Mt=c.Mt,l.ot[0].ut=a.Ft().Nt(c.Mt,d.Wt),l.dt=c.Ht??this.O.Ut(l.ot[0].ut/a.Ft().$t()),l.ot[0].wt=i,l.ot[0]._t=n.jt(i),l.lt=gu):l.lt=null})}}class yu extends Ue{constructor(e){super(),this.qt=e}et({context:e,bitmapSize:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(this.qt===null)return;const a=this.qt.Yt.It,o=this.qt.Kt.It;if(!a&&!o)return;const l=Math.round(this.qt._t*i),c=Math.round(this.qt.ut*n);e.lineCap="butt",a&&l>=0&&(e.lineWidth=Math.floor(this.qt.Yt.ct*i),e.strokeStyle=this.qt.Yt.R,e.fillStyle=this.qt.Yt.R,et(e,this.qt.Yt.Gt),function(d,h,u,m){d.beginPath();const x=d.lineWidth%2?.5:0;d.moveTo(h+x,u),d.lineTo(h+x,m),d.stroke()}(e,l,0,t.height)),o&&c>=0&&(e.lineWidth=Math.floor(this.qt.Kt.ct*n),e.strokeStyle=this.qt.Kt.R,e.fillStyle=this.qt.Kt.R,et(e,this.qt.Kt.Gt),Xa(e,c,0,t.width))}}class wu{constructor(e,t){this.xt=!0,this.Zt={Yt:{ct:1,Gt:0,R:"",It:!1},Kt:{ct:1,Gt:0,R:"",It:!1},_t:0,ut:0},this.Xt=new yu(this.Zt),this.Jt=e,this.yt=t}Pt(){this.xt=!0}Tt(e){return this.xt&&(this.Rt(),this.xt=!1),this.Xt}Rt(){const e=this.Jt.It(),t=this.yt.Qt().N().crosshair,i=this.Zt;if(t.mode===2)return i.Kt.It=!1,void(i.Yt.It=!1);i.Kt.It=e&&this.Jt.ti(this.yt),i.Yt.It=e&&this.Jt.ii(),i.Kt.ct=t.horzLine.width,i.Kt.Gt=t.horzLine.style,i.Kt.R=t.horzLine.color,i.Yt.ct=t.vertLine.width,i.Yt.Gt=t.vertLine.style,i.Yt.R=t.vertLine.color,i._t=this.Jt.ni(),i.ut=this.Jt.si()}}function Nu(s,e,t,i,n,a){s.fillRect(e+a,t,i-2*a,a),s.fillRect(e+a,t+n-a,i-2*a,a),s.fillRect(e,t,a,n),s.fillRect(e+i-a,t,a,n)}function di(s,e,t,i,n,a){s.save(),s.globalCompositeOperation="copy",s.fillStyle=a,s.fillRect(e,t,i,n),s.restore()}function mn(s,e,t,i,n,a){s.beginPath(),s.roundRect?s.roundRect(e,t,i,n,a):(s.lineTo(e+i-a[1],t),a[1]!==0&&s.arcTo(e+i,t,e+i,t+a[1],a[1]),s.lineTo(e+i,t+n-a[2]),a[2]!==0&&s.arcTo(e+i,t+n,e+i-a[2],t+n,a[2]),s.lineTo(e+a[3],t+n),a[3]!==0&&s.arcTo(e,t+n,e,t+n-a[3],a[3]),s.lineTo(e,t+a[0]),a[0]!==0&&s.arcTo(e,t,e+a[0],t,a[0]))}function pn(s,e,t,i,n,a,o=0,l=[0,0,0,0],c=""){if(s.save(),!o||!c||c===a)return mn(s,e,t,i,n,l),s.fillStyle=a,s.fill(),void s.restore();const d=o/2;var h;mn(s,e+d,t+d,i-o,n-o,(h=-d,l.map(u=>u===0?u:u+h))),a!=="transparent"&&(s.fillStyle=a,s.fill()),c!=="transparent"&&(s.lineWidth=o,s.strokeStyle=c,s.closePath(),s.stroke()),s.restore()}function eo(s,e,t,i,n,a,o){s.save(),s.globalCompositeOperation="copy";const l=s.createLinearGradient(0,0,0,n);l.addColorStop(0,a),l.addColorStop(1,o),s.fillStyle=l,s.fillRect(e,t,i,n),s.restore()}class fn{constructor(e,t){this.ht(e,t)}ht(e,t){this.qt=e,this.ei=t}$t(e,t){return this.qt.It?e.P+e.A+e.I:0}st(e,t,i,n){if(!this.qt.It||this.qt.ri.length===0)return;const a=this.qt.R,o=this.ei.Z,l=e.useBitmapCoordinateSpace(c=>{const d=c.context;d.font=t.k;const h=this.hi(c,t,i,n),u=h.ai;return h.li?pn(d,u.oi,u._i,u.ui,u.ci,o,u.di,[u.ft,0,0,u.ft],o):pn(d,u.fi,u._i,u.ui,u.ci,o,u.di,[0,u.ft,u.ft,0],o),this.qt.pi&&(d.fillStyle=a,d.fillRect(u.fi,u.mi,u.wi-u.fi,u.Mi)),this.qt.gi&&(d.fillStyle=t.D,d.fillRect(h.li?u.bi-u.di:0,u._i,u.di,u.Si-u._i)),h});e.useMediaCoordinateSpace(({context:c})=>{const d=l.xi;c.font=t.k,c.textAlign=l.li?"right":"left",c.textBaseline="middle",c.fillStyle=a,c.fillText(this.qt.ri,d.Ci,(d._i+d.Si)/2+d.yi)})}hi(e,t,i,n){const{context:a,bitmapSize:o,mediaSize:l,horizontalPixelRatio:c,verticalPixelRatio:d}=e,h=this.qt.pi||!this.qt.Pi?t.C:0,u=this.qt.ki?t.S:0,m=t.A+this.ei.Ti,x=t.I+this.ei.Ri,b=t.V,f=t.B,g=this.qt.ri,p=t.P,v=i.Di(a,g),S=Math.ceil(i.Ii(a,g)),j=p+m+x,k=t.S+b+f+S+h,C=Math.max(1,Math.floor(d));let E=Math.round(j*d);E%2!=C%2&&(E+=1);const T=u>0?Math.max(1,Math.floor(u*c)):0,D=Math.round(k*c),O=Math.round(h*c),M=this.ei.Vi??this.ei.Bi??this.ei.Ei,R=Math.round(M*d)-Math.floor(.5*d),L=Math.floor(R+C/2-E/2),$=L+E,z=n==="right",V=z?l.width-u:u,q=z?o.width-T:T;let Z,ae,A;return z?(Z=q-D,ae=q-O,A=V-h-b-u):(Z=q+D,ae=q+O,A=V+h+b),{li:z,ai:{_i:L,mi:R,Si:$,ui:D,ci:E,ft:2*c,di:T,oi:Z,fi:q,wi:ae,Mi:C,bi:o.width},xi:{_i:L/d,Si:$/d,Ci:A,yi:v}}}}class hi{constructor(e){this.Ai={Ei:0,Z:"#000",Ri:0,Ti:0},this.Li={ri:"",It:!1,pi:!0,Pi:!1,Ht:"",R:"#FFF",gi:!1,ki:!1},this.zi={ri:"",It:!1,pi:!1,Pi:!0,Ht:"",R:"#FFF",gi:!0,ki:!0},this.xt=!0,this.Oi=new(e||fn)(this.Li,this.Ai),this.Ni=new(e||fn)(this.zi,this.Ai)}ri(){return this.Fi(),this.Li.ri}Ei(){return this.Fi(),this.Ai.Ei}Pt(){this.xt=!0}$t(e,t=!1){return Math.max(this.Oi.$t(e,t),this.Ni.$t(e,t))}Wi(){return this.Ai.Vi??null}Hi(){return this.Ai.Vi??this.Ai.Bi??this.Ei()}Ui(e){this.Ai.Bi=e??void 0}$i(){return this.Fi(),this.Li.It||this.zi.It}ji(){return this.Fi(),this.Li.It}Tt(e){return this.Fi(),this.Li.pi=this.Li.pi&&e.N().ticksVisible,this.zi.pi=this.zi.pi&&e.N().ticksVisible,this.Oi.ht(this.Li,this.Ai),this.Ni.ht(this.zi,this.Ai),this.Oi}qi(){return this.Fi(),this.Oi.ht(this.Li,this.Ai),this.Ni.ht(this.zi,this.Ai),this.Ni}Fi(){this.xt&&(this.Li.pi=!0,this.zi.pi=!1,this.Yi(this.Li,this.zi,this.Ai))}}class ju extends hi{constructor(e,t,i){super(),this.Jt=e,this.Ki=t,this.Gi=i}Yi(e,t,i){if(e.It=!1,this.Jt.N().mode===2)return;const n=this.Jt.N().horzLine;if(!n.labelVisible)return;const a=this.Ki.Lt();if(!this.Jt.It()||this.Ki.Zi()||a===null)return;const o=this.Ki.Xi().G(n.labelBackgroundColor);i.Z=o.Z,e.R=o.X;const l=2/12*this.Ki.P();i.Ti=l,i.Ri=l;const c=this.Gi(this.Ki);i.Ei=c.Ei,e.ri=this.Ki.Ji(c.Mt,a),e.It=!0}}const _u=/[1-9]/g;class to{constructor(){this.qt=null}ht(e){this.qt=e}st(e,t){if(this.qt===null||this.qt.It===!1||this.qt.ri.length===0)return;const i=e.useMediaCoordinateSpace(({context:m})=>(m.font=t.k,Math.round(t.Qi.Ii(m,P(this.qt).ri,_u))));if(i<=0)return;const n=t.tn,a=i+2*n,o=a/2,l=this.qt.nn;let c=this.qt.Ei,d=Math.floor(c-o)+.5;d<0?(c+=Math.abs(0-d),d=Math.floor(c-o)+.5):d+a>l&&(c-=Math.abs(l-(d+a)),d=Math.floor(c-o)+.5);const h=d+a,u=Math.ceil(0+t.S+t.C+t.A+t.P+t.I);e.useBitmapCoordinateSpace(({context:m,horizontalPixelRatio:x,verticalPixelRatio:b})=>{const f=P(this.qt);m.fillStyle=f.Z;const g=Math.round(d*x),p=Math.round(0*b),v=Math.round(h*x),S=Math.round(u*b),j=Math.round(2*x);if(m.beginPath(),m.moveTo(g,p),m.lineTo(g,S-j),m.arcTo(g,S,g+j,S,j),m.lineTo(v-j,S),m.arcTo(v,S,v,S-j,j),m.lineTo(v,p),m.fill(),f.pi){const k=Math.round(f.Ei*x),C=p,E=Math.round((C+t.C)*b);m.fillStyle=f.R;const T=Math.max(1,Math.floor(x)),D=Math.floor(.5*x);m.fillRect(k-D,C,T,E-C)}}),e.useMediaCoordinateSpace(({context:m})=>{const x=P(this.qt),b=0+t.S+t.C+t.A+t.P/2;m.font=t.k,m.textAlign="left",m.textBaseline="middle",m.fillStyle=x.R;const f=t.Qi.Di(m,"Apr0");m.translate(d+n,b+f),m.fillText(x.ri,0,0)})}}class Su{constructor(e,t,i){this.xt=!0,this.Xt=new to,this.Zt={It:!1,Z:"#4c525e",R:"white",ri:"",nn:0,Ei:NaN,pi:!0},this.Ct=e,this.sn=t,this.Gi=i}Pt(){this.xt=!0}Tt(){return this.xt&&(this.Rt(),this.xt=!1),this.Xt.ht(this.Zt),this.Xt}Rt(){const e=this.Zt;if(e.It=!1,this.Ct.N().mode===2)return;const t=this.Ct.N().vertLine;if(!t.labelVisible)return;const i=this.sn.Et();if(i.Zi())return;e.nn=i.nn();const n=this.Gi();if(n===null)return;e.Ei=n.Ei;const a=i.en(this.Ct.Bt());e.ri=i.rn(P(a)),e.It=!0;const o=this.sn.Xi().G(t.labelBackgroundColor);e.Z=o.Z,e.R=o.X,e.pi=i.N().ticksVisible}}class so{constructor(){this.hn=null,this.an=0}ln(){return this.an}_n(e){this.an=e}Ft(){return this.hn}un(e){this.hn=e}cn(e){return[]}dn(){return[]}It(){return!0}}var Lt;(function(s){s[s.Normal=0]="Normal",s[s.Magnet=1]="Magnet",s[s.Hidden=2]="Hidden",s[s.MagnetOHLC=3]="MagnetOHLC"})(Lt||(Lt={}));class ku extends so{constructor(e,t){super(),this.yt=null,this.fn=NaN,this.pn=0,this.vn=!1,this.mn=new Map,this.wn=!1,this.Mn=new WeakMap,this.gn=new WeakMap,this.bn=NaN,this.Sn=NaN,this.xn=NaN,this.Cn=NaN,this.sn=e,this.yn=t,this.Pn=((n,a)=>o=>{const l=a(),c=n();if(o===P(this.yt).kn())return{Mt:c,Ei:l};{const d=P(o.Lt());return{Mt:o.Tn(l,d),Ei:l}}})(()=>this.fn,()=>this.Sn);const i=((n,a)=>()=>{const o=this.sn.Et().Rn(n()),l=a();return o&&Number.isFinite(l)?{wt:o,Ei:l}:null})(()=>this.pn,()=>this.ni());this.Dn=new Su(this,e,i)}N(){return this.yn}In(e,t){this.xn=e,this.Cn=t}Vn(){this.xn=NaN,this.Cn=NaN}Bn(){return this.xn}En(){return this.Cn}An(e,t,i){this.wn||(this.wn=!0),this.vn=!0,this.Ln(e,t,i)}Bt(){return this.pn}ni(){return this.bn}si(){return this.Sn}It(){return this.vn}zn(){this.vn=!1,this.On(),this.fn=NaN,this.bn=NaN,this.Sn=NaN,this.yt=null,this.Vn(),this.Nn()}Fn(e){if(!this.yn.doNotSnapToHiddenSeriesIndices)return e;const t=this.sn,i=t.Et();let n=null,a=null;for(const d of t.Wn()){const h=d.Un().Hn(e,-1);if(h){if(h.$n===e)return e;(n===null||h.$n>n)&&(n=h.$n)}const u=d.Un().Hn(e,1);if(u){if(u.$n===e)return e;(a===null||u.$nMath.abs(l-i.jt(d)));return o[c.indexOf(Math.min(...c))]}jn(e){let t=this.Mn.get(e);t||(t=new wu(this,e),this.Mn.set(e,t));let i=this.gn.get(e);return i||(i=new vu(this.sn,this,e),this.gn.set(e,i)),[t,i]}ti(e){return e===this.yt&&this.yn.horzLine.visible}ii(){return this.yn.vertLine.visible}qn(e,t){this.vn&&this.yt===e||this.mn.clear();const i=[];return this.yt===e&&i.push(this.Yn(this.mn,t,this.Pn)),i}dn(){return this.vn?[this.Dn]:[]}Kn(){return this.yt}Nn(){this.sn.Gn().forEach(e=>{this.Mn.get(e)?.Pt(),this.gn.get(e)?.Pt()}),this.mn.forEach(e=>e.Pt()),this.Dn.Pt()}Zn(e){return e&&!e.kn().Zi()?e.kn():null}Ln(e,t,i){this.Xn(e,t,i)&&this.Nn()}Xn(e,t,i){const n=this.bn,a=this.Sn,o=this.fn,l=this.pn,c=this.yt,d=this.Zn(i);this.pn=e,this.bn=isNaN(e)?NaN:this.sn.Et().jt(e),this.yt=i;const h=d!==null?d.Lt():null;return d!==null&&h!==null?(this.fn=t,this.Sn=d.Nt(t,h)):(this.fn=NaN,this.Sn=NaN),n!==this.bn||a!==this.Sn||l!==this.pn||o!==this.fn||c!==this.yt}On(){const e=this.sn.Jn().map(i=>i.Un().Qn()).filter(hn),t=e.length===0?null:Math.max(...e);this.pn=t!==null?t:NaN}Yn(e,t,i){let n=e.get(t);return n===void 0&&(n=new ju(this,t,i),e.set(t,n)),n}}function ui(s){return s==="left"||s==="right"}class me{constructor(e){this.ts=new Map,this.ns=[],this.ss=e}es(e,t){const i=function(n,a){return n===void 0?a:{rs:Math.max(n.rs,a.rs),hs:n.hs||a.hs}}(this.ts.get(e),t);this.ts.set(e,i)}ls(){return this.ss}_s(e){const t=this.ts.get(e);return t===void 0?{rs:this.ss}:{rs:Math.max(this.ss,t.rs),hs:t.hs}}us(){this.cs(),this.ns=[{ds:0}]}fs(e){this.cs(),this.ns=[{ds:1,Wt:e}]}ps(e){this.vs(),this.ns.push({ds:5,Wt:e})}cs(){this.vs(),this.ns.push({ds:6})}ws(){this.cs(),this.ns=[{ds:4}]}Ms(e){this.cs(),this.ns.push({ds:2,Wt:e})}gs(e){this.cs(),this.ns.push({ds:3,Wt:e})}bs(){return this.ns}Ss(e){for(const t of e.ns)this.xs(t);this.ss=Math.max(this.ss,e.ss),e.ts.forEach((t,i)=>{this.es(i,t)})}static Cs(){return new me(2)}static ys(){return new me(3)}xs(e){switch(e.ds){case 0:this.us();break;case 1:this.fs(e.Wt);break;case 2:this.Ms(e.Wt);break;case 3:this.gs(e.Wt);break;case 4:this.ws();break;case 5:this.ps(e.Wt);break;case 6:this.vs()}}vs(){const e=this.ns.findIndex(t=>t.ds===5);e!==-1&&this.ns.splice(e,1)}}class io{formatTickmarks(e){return e.map(t=>this.format(t))}}const xn=".";function De(s,e){if(!Pt(s))return"n/a";if(!rs(e))throw new TypeError("invalid length");if(e<0||e>16)throw new TypeError("invalid length");return e===0?s.toString():("0000000000000000"+s.toString()).slice(-e)}class mi extends io{constructor(e,t){if(super(),t||(t=1),Pt(e)&&rs(e)||(e=100),e<0)throw new TypeError("invalid base");this.Ki=e,this.Ps=t,this.ks()}format(e){const t=e<0?"−":"";return e=Math.abs(e),t+this.Ts(e)}ks(){if(this.Rs=0,this.Ki>0&&this.Ps>0){let e=this.Ki;for(;e>1;)e/=10,this.Rs++}}Ts(e){const t=this.Ki/this.Ps;let i=Math.floor(e),n="";const a=this.Rs!==void 0?this.Rs:NaN;if(t>1){let o=+(Math.round(e*t)-i*t).toFixed(this.Rs);o>=t&&(o-=t,i+=1),n=xn+De(+o.toFixed(this.Rs)*this.Ps,a)}else i=Math.round(i*t)/t,a>0&&(n=xn+De(0,a));return i.toFixed(0)+n}}class ro extends mi{constructor(e=100){super(e)}format(e){return`${super.format(e)}%`}}class Mu extends io{constructor(e){super(),this.Ds=e}format(e){let t="";return e<0&&(t="-",e=-e),e<995?t+this.Is(e):e<999995?t+this.Is(e/1e3)+"K":e<999999995?(e=1e3*Math.round(e/1e3),t+this.Is(e/1e6)+"M"):(e=1e6*Math.round(e/1e6),t+this.Is(e/1e9)+"B")}Is(e){let t;const i=Math.pow(10,this.Ds);return t=(e=Math.round(e*i)/i)>=1e-15&&e<1?e.toFixed(this.Ds).replace(/\.?0+$/,""):String(e),t.replace(/(\.[1-9]*)0+$/,(n,a)=>a)}}const Cu=/[2-9]/g;class Gs{constructor(e=50){this.Vs=0,this.Bs=1,this.Es=1,this.As={},this.Ls=new Map,this.zs=e}Os(){this.Vs=0,this.Ls.clear(),this.Bs=1,this.Es=1,this.As={}}Ii(e,t,i){return this.Ns(e,t,i).width}Di(e,t,i){const n=this.Ns(e,t,i);return((n.actualBoundingBoxAscent||0)-(n.actualBoundingBoxDescent||0))/2}Ns(e,t,i){const n=i||Cu,a=String(t).replace(n,"0");if(this.Ls.has(a))return _e(this.Ls.get(a)).Fs;if(this.Vs===this.zs){const l=this.As[this.Es];delete this.As[this.Es],this.Ls.delete(l),this.Es++,this.Vs--}e.save(),e.textBaseline="middle";const o=e.measureText(a);return e.restore(),o.width===0&&t.length||(this.Ls.set(a,{Fs:o,Ws:this.Bs}),this.As[this.Bs]=a,this.Vs++,this.Bs++),o}}class Eu{constructor(e){this.Hs=null,this.M=null,this.Us="right",this.$s=e}js(e,t,i){this.Hs=e,this.M=t,this.Us=i}st(e){this.M!==null&&this.Hs!==null&&this.Hs.st(e,this.M,this.$s,this.Us)}}class no{constructor(e,t,i){this.qs=e,this.$s=new Gs(50),this.Ys=t,this.O=i,this.F=-1,this.Xt=new Eu(this.$s)}Tt(){const e=this.O.Ks(this.Ys);if(e===null)return null;const t=e.Gs(this.Ys)?e.Zs():this.Ys.Ft();if(t===null)return null;const i=e.Xs(t);if(i==="overlay")return null;const n=this.O.Js();return n.P!==this.F&&(this.F=n.P,this.$s.Os()),this.Xt.js(this.qs.qi(),n,i),this.Xt}}class Tu extends Ue{constructor(){super(...arguments),this.qt=null}ht(e){this.qt=e}Qs(e,t){if(!this.qt?.It)return null;const{ut:i,ct:n,te:a}=this.qt;return t>=i-n-7&&t<=i+n+7?{ie:this.qt,ne:Math.abs(t-i),se:2,ee:"price-line",te:a}:null}et({context:e,bitmapSize:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(this.qt===null||this.qt.It===!1)return;const a=Math.round(this.qt.ut*n);a<0||a>t.height||(e.lineCap="butt",e.strokeStyle=this.qt.R,e.lineWidth=Math.floor(this.qt.ct*i),et(e,this.qt.Gt),Xa(e,a,0,t.width))}}class wr{constructor(e){this.re={ut:0,R:"rgba(0, 0, 0, 0)",ct:1,Gt:0,It:!1},this.he=new Tu,this.xt=!0,this.ae=e,this.le=e.Qt(),this.he.ht(this.re)}Pt(){this.xt=!0}Tt(){return this.ae.It()?(this.xt&&(this.oe(),this.xt=!1),this.he):null}}class Ru extends wr{constructor(e){super(e)}oe(){this.re.It=!1;const e=this.ae.Ft(),t=e._e()._e;if(t!==2&&t!==3)return;const i=this.ae.N();if(!i.baseLineVisible||!this.ae.It())return;const n=this.ae.Lt();n!==null&&(this.re.It=!0,this.re.ut=e.Nt(n.Wt,n.Wt),this.re.R=i.baseLineColor,this.re.ct=i.baseLineWidth,this.re.Gt=i.baseLineStyle)}}class Pu extends Ue{constructor(){super(...arguments),this.qt=null}ht(e){this.qt=e}ue(){return this.qt}et({context:e,horizontalPixelRatio:t,verticalPixelRatio:i}){const n=this.qt;if(n===null)return;const a=Math.max(1,Math.floor(t)),o=a%2/2,l=Math.round(n.ce.x*t)+o,c=n.ce.y*i;e.fillStyle=n.de,e.beginPath();const d=Math.max(2,1.5*n.fe)*t;e.arc(l,c,d,0,2*Math.PI,!1),e.fill(),e.fillStyle=n.pe,e.beginPath(),e.arc(l,c,n.ft*t,0,2*Math.PI,!1),e.fill(),e.lineWidth=a,e.strokeStyle=n.ve,e.beginPath(),e.arc(l,c,n.ft*t+a/2,0,2*Math.PI,!1),e.stroke()}}const Lu=[{me:0,we:.25,Me:4,ge:10,be:.25,Se:0,xe:.4,Ce:.8},{me:.25,we:.525,Me:10,ge:14,be:0,Se:0,xe:.8,Ce:0},{me:.525,we:1,Me:14,ge:14,be:0,Se:0,xe:0,Ce:0}];class Au{constructor(e){this.Xt=new Pu,this.xt=!0,this.ye=!0,this.Pe=performance.now(),this.ke=this.Pe-1,this.Te=e}Re(){this.ke=this.Pe-1,this.Pt()}De(){if(this.Pt(),this.Te.N().lastPriceAnimation===2){const e=performance.now(),t=this.ke-e;if(t>0)return void(t<650&&(this.ke+=2600));this.Pe=e,this.ke=e+2600}}Pt(){this.xt=!0}Ie(){this.ye=!0}It(){return this.Te.N().lastPriceAnimation!==0}Ve(){switch(this.Te.N().lastPriceAnimation){case 0:return!1;case 1:return!0;case 2:return performance.now()<=this.ke}}Tt(){return this.xt?(this.Rt(),this.xt=!1,this.ye=!1):this.ye&&(this.Be(),this.ye=!1),this.Xt}Rt(){this.Xt.ht(null);const e=this.Te.Qt().Et(),t=e.Ee(),i=this.Te.Lt();if(t===null||i===null)return;const n=this.Te.Ae(!0);if(n.Le||!t.ze(n.$n))return;const a={x:e.jt(n.$n),y:this.Te.Ft().Nt(n.Mt,i.Wt)},o=n.R,l=this.Te.N().lineWidth,c=this.Oe(this.Ne(),o);this.Xt.ht({de:o,fe:l,pe:c.pe,ve:c.ve,ft:c.ft,ce:a})}Be(){const e=this.Xt.ue();if(e!==null){const t=this.Oe(this.Ne(),e.de);e.pe=t.pe,e.ve=t.ve,e.ft=t.ft}}Ne(){return this.Ve()?performance.now()-this.Pe:2599}Fe(e,t,i,n){const a=i+(n-i)*t;return this.Te.Qt().Xi().Y(e,a)}Oe(e,t){const i=e%2600/2600;let n;for(const d of Lu)if(i>=d.me&&i<=d.we){n=d;break}pe(n!==void 0,"Last price animation internal logic error");const a=(i-n.me)/(n.we-n.me);return{pe:this.Fe(t,a,n.be,n.Se),ve:this.Fe(t,a,n.xe,n.Ce),ft:(o=a,l=n.Me,c=n.ge,l+(c-l)*o)};var o,l,c}}class Ou extends wr{constructor(e){super(e)}oe(){const e=this.re;e.It=!1;const t=this.ae.N();if(!t.priceLineVisible||!this.ae.It())return;const i=this.ae.Ae(t.priceLineSource===0);i.Le||(e.It=!0,e.ut=i.Ei,e.R=this.ae.We(i.R),e.ct=t.priceLineWidth,e.Gt=t.priceLineStyle)}}class zu extends hi{constructor(e){super(),this.Jt=e}Yi(e,t,i){e.It=!1,t.It=!1;const n=this.Jt;if(!n.It())return;const a=n.N(),o=a.lastValueVisible,l=n.He()!=="",c=a.seriesLastValueMode===0,d=n.Ae(!1);if(d.Le)return;o&&(e.ri=this.Ue(d,o,c),e.It=e.ri.length!==0),(l||c)&&(t.ri=this.$e(d,o,l,c),t.It=t.ri.length>0);const h=n.We(d.R),u=this.Jt.Qt().Xi().G(h);i.Z=u.Z,i.Ei=d.Ei,t.Ht=n.Qt().Ut(d.Ei/n.Ft().$t()),e.Ht=h,e.R=u.X,t.R=u.X}$e(e,t,i,n){let a="";const o=this.Jt.He();return i&&o.length!==0&&(a+=`${o} `),t&&n&&(a+=this.Jt.Ft().je()?e.qe:e.Ye),a.trim()}Ue(e,t,i){return t?i?this.Jt.Ft().je()?e.Ye:e.qe:e.ri:""}}function bn(s,e,t,i){const n=Number.isFinite(e),a=Number.isFinite(t);return n&&a?s(e,t):n||a?n?e:t:i}class ye{constructor(e,t){this.Ke=e,this.Ge=t}Ze(e){return e!==null&&this.Ke===e.Ke&&this.Ge===e.Ge}Xe(){return new ye(this.Ke,this.Ge)}Je(){return this.Ke}Qe(){return this.Ge}tr(){return this.Ge-this.Ke}Zi(){return this.Ge===this.Ke||Number.isNaN(this.Ge)||Number.isNaN(this.Ke)}Ss(e){return e===null?this:new ye(bn(Math.min,this.Je(),e.Je(),-1/0),bn(Math.max,this.Qe(),e.Qe(),1/0))}ir(e){if(!Pt(e)||this.Ge-this.Ke===0)return;const t=.5*(this.Ge+this.Ke);let i=this.Ge-t,n=this.Ke-t;i*=e,n*=e,this.Ge=t+i,this.Ke=t+n}nr(e){Pt(e)&&(this.Ge+=e,this.Ke+=e)}sr(){return{minValue:this.Ke,maxValue:this.Ge}}static er(e){return e===null?null:new ye(e.minValue,e.maxValue)}}class Qs{constructor(e,t){this.rr=e,this.hr=t||null}ar(){return this.rr}lr(){return this.hr}sr(){return{priceRange:this.rr===null?null:this.rr.sr(),margins:this.hr||void 0}}static er(e){return e===null?null:new Qs(ye.er(e.priceRange),e.margins)}}const Iu=[2,4,8,16,32,64,128,256,512],$u="Custom series with conflation reducer must have a priceValueBuilder method";class Du extends wr{constructor(e,t){super(e),this._r=t}oe(){const e=this.re;e.It=!1;const t=this._r.N();if(!this.ae.It()||!t.lineVisible)return;const i=this._r.ur();i!==null&&(e.It=!0,e.ut=i,e.R=t.color,e.ct=t.lineWidth,e.Gt=t.lineStyle,e.te=this._r.N().id)}}class Bu extends hi{constructor(e,t){super(),this.Te=e,this._r=t}Yi(e,t,i){e.It=!1,t.It=!1;const n=this._r.N(),a=n.axisLabelVisible,o=n.title!=="",l=this.Te;if(!a||!l.It())return;const c=this._r.ur();if(c===null)return;o&&(t.ri=n.title,t.It=!0),t.Ht=l.Qt().Ut(c/l.Ft().$t()),e.ri=this.cr(n.price),e.It=!0;const d=this.Te.Qt().Xi().G(n.axisLabelColor||n.color);i.Z=d.Z;const h=n.axisLabelTextColor||d.X;e.R=h,t.R=h,i.Ei=c}cr(e){const t=this.Te.Lt();return t===null?"":this.Te.Ft().Ji(e,t.Wt)}}class Fu{constructor(e,t){this.Te=e,this.yn=t,this.dr=new Du(e,this),this.qs=new Bu(e,this),this.pr=new no(this.qs,e,e.Qt())}vr(e){Me(this.yn,e),this.Pt(),this.Te.Qt().mr()}N(){return this.yn}wr(){return this.dr}Mr(){return this.pr}gr(){return this.qs}Pt(){this.dr.Pt(),this.qs.Pt()}ur(){const e=this.Te,t=e.Ft();if(e.Qt().Et().Zi()||t.Zi())return null;const i=e.Lt();return i===null?null:t.Nt(this.yn.price,i.Wt)}}class Uu{constructor(){this.br=new WeakMap}Sr(e,t,i){const n=1/t*i;if(e>=n)return 1;const a=n/e,o=Math.pow(2,Math.floor(Math.log2(a)));return Math.min(o,512)}Cr(e,t,i,n=!1,a){if(e.length===0||t<=1)return e;const o=this.yr(t);if(o<=1)return e;const l=this.Pr(e);let c=l.kr.get(o);return c!==void 0||(c=this.Tr(e,o,i,n,a,l.kr),l.kr.set(o,c)),c}Rr(e,t,i,n,a=!1,o){if(i<1||e.length===0)return e;const l=this.Pr(e),c=l.kr.get(i);if(!c)return this.Cr(e,i,n,a,o);const d=this.Dr(e,t,i,c,a,n,o);return l.kr.set(i,d),d}yr(e){if(e<=2)return 2;for(const t of Iu)if(e<=t)return t;return 512}Ir(e){if(e.length===0)return 0;const t=e[0],i=e[e.length-1];return 31*e.length+17*t.$n+13*i.$n}Tr(e,t,i,n=!1,a,o=new Map){if(t===2)return this.Vr(e,2,i,n,a);const l=t/2;let c=o.get(l);return c||(c=this.Tr(e,l,i,n,a,o),o.set(l,c)),this.Br(c,i,n,a)}Vr(e,t,i,n=!1,a){const o=this.Er(e,t,i,n,a);return this.Ar(o,n)}Br(e,t,i=!1,n){const a=this.Er(e,2,t,i,n);return this.Ar(a,i)}Er(e,t,i,n=!1,a){const o=[];for(let l=0;l=t){const c=this.Lr(e[l],e[l+1],i,n,a);c.zr=!1,o.push(c)}else if(o.length===0)o.push(this.Or(e[l],!0));else{const c=o[o.length-1];o[o.length-1]=this.Nr(c,e[l],i,n,a)}return o}Fr(e,t){return(e??1)+(t??1)}Lr(e,t,i,n=!1,a){if(!n||!i||!a){const d=e.Wt[1]>t.Wt[1]?e.Wt[1]:t.Wt[1],h=e.Wt[2]t.Wt[1]?e.qr:t.Wt[1],Yr:e.Yrthis.th(i,t))}Dr(e,t,i,n,a=!1,o,l){if(n.length===0)return n;const c=e.length-1,d=Math.floor(c/i)*i;if(Math.min(d+i,e.length)-di){const h=e.slice();return h[h.length-1]=t,this.Cr(h,i,o,a,l)}if(Math.floor((c-1)/i)===Math.floor(c/i)||n.length===1){const h=Math.min(d+i,e.length),u=h-d;if(u<=0)return n;const m=u===1?this.Or(d===c?t:e[d],!0):this.Jr(e,d,h,c,t,o,a,l);return n[n.length-1]=this.th(m,a),n}{const h=e.slice();return h[h.length-1]=t,this.Cr(h,i,o,a,l)}}Or(e,t=!1){return{Wr:e.$n,Hr:e.$n,Ur:e.wt,$r:e.wt,jr:e.Wt[0],qr:e.Wt[1],Yr:e.Wt[2],Kr:e.Wt[3],Gr:e.Gr??1,Zr:e.ue,zr:t}}Pr(e){const t=this.ih(e),i=this.Ir(e);return t.nh!==i&&(t.kr.clear(),t.nh=i),t}ih(e){let t=this.br.get(e);return t===void 0&&(t={nh:this.Ir(e),kr:new Map},this.br.set(e,t)),t}}class qu extends so{constructor(e){super(),this.sn=e}Qt(){return this.sn}}const Wu={Bar:(s,e,t,i)=>{const n=e.upColor,a=e.downColor,o=P(s(t,i)),l=Ye(o.Wt[0])<=Ye(o.Wt[3]);return{sh:o.R??(l?n:a)}},Candlestick:(s,e,t,i)=>{const n=e.upColor,a=e.downColor,o=e.borderUpColor,l=e.borderDownColor,c=e.wickUpColor,d=e.wickDownColor,h=P(s(t,i)),u=Ye(h.Wt[0])<=Ye(h.Wt[3]);return{sh:h.R??(u?n:a),eh:h.Ht??(u?o:l),rh:h.hh??(u?c:d)}},Custom:(s,e,t,i)=>({sh:P(s(t,i)).R??e.color}),Area:(s,e,t,i)=>{const n=P(s(t,i));return{sh:n.vt??e.lineColor,vt:n.vt??e.lineColor,ah:n.ah??e.topColor,oh:n.oh??e.bottomColor}},Baseline:(s,e,t,i)=>{const n=P(s(t,i));return{sh:n.Wt[3]>=e.baseValue.price?e.topLineColor:e.bottomLineColor,_h:n._h??e.topLineColor,uh:n.uh??e.bottomLineColor,dh:n.dh??e.topFillColor1,fh:n.fh??e.topFillColor2,ph:n.ph??e.bottomFillColor1,mh:n.mh??e.bottomFillColor2}},Line:(s,e,t,i)=>{const n=P(s(t,i));return{sh:n.R??e.color,vt:n.R??e.color}},Histogram:(s,e,t,i)=>({sh:P(s(t,i)).R??e.color})};class Hu{constructor(e){this.wh=(t,i)=>i!==void 0?i.Wt:this.Te.Un().Mh(t),this.Te=e,this.gh=Wu[e.bh()]}Sh(e,t){return this.gh(this.wh,this.Te.N(),e,t)}}function ao(s,e,t,i,n=0,a=e.length){let o=a-n;for(;0>1,c=n+l;i(e[c],t)===s?(n=c+1,o-=l+1):o=l}return n}const mt=ao.bind(null,!0),Nr=ao.bind(null,!1);var gn;(function(s){s[s.NearestLeft=-1]="NearestLeft",s[s.None=0]="None",s[s.NearestRight=1]="NearestRight"})(gn||(gn={}));const Ge=30;class Vu{constructor(){this.xh=[],this.Ch=new Map,this.yh=new Map,this.Ph=[]}kh(){return this.Th()>0?this.xh[this.xh.length-1]:null}Rh(){return this.Th()>0?this.Dh(0):null}Qn(){return this.Th()>0?this.Dh(this.xh.length-1):null}Th(){return this.xh.length}Zi(){return this.Th()===0}ze(e){return this.Ih(e,0)!==null}Mh(e){return this.Hn(e)}Hn(e,t=0){const i=this.Ih(e,t);return i===null?null:{...this.Vh(i),$n:this.Dh(i)}}Bh(){return this.xh}Eh(e,t,i){if(this.Zi())return null;let n=null;for(const a of i)n=js(n,this.Ah(e,t,a));return n}ht(e){this.yh.clear(),this.Ch.clear(),this.xh=e,this.Ph=e.map(t=>t.$n)}Lh(){return this.Ph}Dh(e){return this.xh[e].$n}Vh(e){return this.xh[e]}Ih(e,t){const i=this.zh(e);if(i===null&&t!==0)switch(t){case-1:return this.Oh(e);case 1:return this.Nh(e);default:throw new TypeError("Unknown search mode")}return i}Oh(e){let t=this.Fh(e);return t>0&&(t-=1),t!==this.xh.length&&this.Dh(t)t.$nt.$n>i)}Hh(e,t,i){let n=null;for(let a=e;an.$h&&(n.$h=o)))}return n}Ah(e,t,i){if(this.Zi())return null;let n=null;const a=P(this.Rh()),o=P(this.Qn()),l=Math.max(e,a),c=Math.min(t,o),d=Math.ceil(l/Ge)*Ge,h=Math.max(d,Math.floor(c/Ge)*Ge);{const m=this.Fh(l),x=this.Wh(Math.min(c,d,t));n=js(n,this.Hh(m,x,i))}let u=this.Ch.get(i);u===void 0&&(u=new Map,this.Ch.set(i,u));for(let m=Math.max(d+1,l);mnew Gu(i));return this.Xh={Kh:e,Gh:t},t}Qs(e,t){return this.Jh.hitTest?.(e,t)??null}}let Qu=class extends oo{cn(){return[]}};class Yu{constructor(e){this.jh=e}st(e,t,i){this.jh.draw(e,Ys)}qh(e,t,i){this.jh.drawBackground?.(e,Ys)}}class vn{constructor(e){this.Ls=null,this.Yh=e}Tt(){const e=this.Yh.renderer();if(e===null)return null;if(this.Ls?.Kh===e)return this.Ls.Gh;const t=new Yu(e);return this.Ls={Kh:e,Gh:t},t}Zh(){return this.Yh.zOrder?.()??"normal"}}function lo(s){return{ri:s.text(),Ei:s.coordinate(),Vi:s.fixedCoordinate?.(),R:s.textColor(),Z:s.backColor(),It:s.visible?.()??!0,pi:s.tickVisible?.()??!0}}class Ju{constructor(e,t){this.Xt=new to,this.ta=e,this.ia=t}Tt(){return this.Xt.ht({nn:this.ia.nn(),...lo(this.ta)}),this.Xt}}class Xu extends hi{constructor(e,t){super(),this.ta=e,this.Ki=t}Yi(e,t,i){const n=lo(this.ta);i.Z=n.Z,e.R=n.R;const a=2/12*this.Ki.P();i.Ti=a,i.Ri=a,i.Ei=n.Ei,i.Vi=n.Vi,e.ri=n.ri,e.It=n.It,e.pi=n.pi}}class Zu extends oo{constructor(e,t){super(e),this.na=null,this.sa=null,this.ea=null,this.ra=null,this.Te=t}dn(){const e=this.Jh.timeAxisViews?.()??[];if(this.na?.Kh===e)return this.na.Gh;const t=this.Te.Qt().Et(),i=e.map(n=>new Ju(n,t));return this.na={Kh:e,Gh:i},i}qn(){const e=this.Jh.priceAxisViews?.()??[];if(this.sa?.Kh===e)return this.sa.Gh;const t=this.Te.Ft(),i=e.map(n=>new Xu(n,t));return this.sa={Kh:e,Gh:i},i}ha(){const e=this.Jh.priceAxisPaneViews?.()??[];if(this.ea?.Kh===e)return this.ea.Gh;const t=e.map(i=>new vn(i));return this.ea={Kh:e,Gh:t},t}aa(){const e=this.Jh.timeAxisPaneViews?.()??[];if(this.ra?.Kh===e)return this.ra.Gh;const t=e.map(i=>new vn(i));return this.ra={Kh:e,Gh:t},t}la(e,t){return this.Jh.autoscaleInfo?.(e,t)??null}}function _s(s,e,t,i){s.forEach(n=>{e(n).forEach(a=>{a.Zh()===t&&i.push(a)})})}function Ss(s){return s.jn()}function em(s){return s.ha()}function tm(s){return s.aa()}const sm=["Area","Line","Baseline"];class pi extends qu{constructor(e,t,i,n,a){super(e),this.qt=Ri(),this.dr=new Ou(this),this.oa=[],this._a=new Ru(this),this.ua=null,this.ca=null,this.da=null,this.fa=[],this.pa=new Uu,this.va=new Map,this.ma=null,this.yn=i,this.wa=t;const o=new zu(this);if(this.mn=[o],this.pr=new no(o,this,e),sm.includes(this.wa)&&(this.ua=new Au(this)),this.Ma(),this.Yh=n(this,this.Qt(),a),this.wa==="Custom"){const l=this.Yh;l.ga&&this.ba(l.ga)}}m(){this.da!==null&&clearTimeout(this.da)}We(e){return this.yn.priceLineColor||e}Ae(e){const t={Le:!0},i=this.Ft();if(this.Qt().Et().Zi()||i.Zi()||this.qt.Zi())return t;const n=this.Qt().Et().Ee(),a=this.Lt();if(n===null||a===null)return t;let o,l;if(e){const u=this.qt.kh();if(u===null)return t;o=u,l=u.$n}else{const u=this.qt.Hn(n.bi(),-1);if(u===null||(o=this.qt.Mh(u.$n),o===null))return t;l=u.$n}const c=o.Wt[3],d=this.Sa().Sh(l,{Wt:o}),h=i.Nt(c,a.Wt);return{Le:!1,Mt:c,ri:i.Ji(c,a.Wt),qe:i.xa(c),Ye:i.Ca(c,a.Wt),R:d.sh,Ei:h,$n:l}}Sa(){return this.ca!==null||(this.ca=new Hu(this)),this.ca}N(){return this.yn}vr(e){const t=this.Qt(),{priceScaleId:i,visible:n,priceFormat:a}=e;i!==void 0&&i!==this.yn.priceScaleId&&t.ya(this,i),n!==void 0&&n!==this.yn.visible&&t.Pa();const o=e.conflationThresholdFactor!==void 0;Me(this.yn,e),Object.prototype.hasOwnProperty.call(e,"autoscaleInfoProvider")&&e.autoscaleInfoProvider===void 0&&(this.yn.autoscaleInfoProvider=void 0),o&&(this.va.clear(),this.Qt().mr()),a!==void 0&&(this.Ma(),t.ka()),t.Ta(this),t.Ra(),this.Yh.Pt("options")}ht(e,t){this.qt.ht(e),this.va.clear();const i=this.Qt().Et().N();i.enableConflation&&i.precomputeConflationOnInit&&this.Da(i.precomputeConflationPriority),this.Ia(),this.ua!==null&&(t&&t.Va?this.ua.De():e.length===0&&this.ua.Re());const n=this.Qt().Ks(this);this.Qt().Ba(n),this.Qt().Ta(this),this.Qt().Ra(),this.Qt().mr()}Ia(){this.Yh.Pt("data")}Ea(e){const t=new Fu(this,e);return this.oa.push(t),this.Qt().Ta(this),t}Aa(e){const t=this.oa.indexOf(e);t!==-1&&this.oa.splice(t,1),this.Qt().Ta(this)}La(){return this.oa}bh(){return this.wa}Lt(){const e=this.za();return e===null?null:{Wt:e.Wt[3],Oa:e.wt}}za(){const e=this.Qt().Et().Ee();if(e===null)return null;const t=e.Na();return this.qt.Hn(t,1)}Un(){return this.qt}ba(e){this.ma=e,this.va.clear()}Fa(){return!!this.Qt().Et().N().enableConflation&&this.Wa()>1}Rr(e){if(!this.Fa())return;const t=this.Wa();if(!this.va.has(t))return;const i=this.wa==="Custom",n=i&&this.ma||void 0,a=i&&this.Yh.Ha?c=>{const d=c,h=this.Yh.Ha(d);return Array.isArray(h)?h:[typeof h=="number"?h:0]}:void 0,o=this.pa.Rr(this.qt.Bh(),e,t,n,i,a),l=Ri();l.ht(o),this.va.set(t,l)}Ua(){const e=this.Qt().Et().N().enableConflation;if(this.wa==="Custom"&&this.ma===null)return this.qt;if(!e)return this.qt;const t=this.Wa(),i=this.va.get(t);return i||(this.$a(t),this.va.get(t)??this.qt)}ja(e){const t=this.qt.Mh(e);return t===null?null:this.wa==="Bar"||this.wa==="Candlestick"||this.wa==="Custom"?{jr:t.Wt[0],qr:t.Wt[1],Yr:t.Wt[2],Kr:t.Wt[3]}:t.Wt[3]}qa(e){const t=[];_s(this.fa,Ss,"top",t);const i=this.ua;return i!==null&&i.It()&&(this.da===null&&i.Ve()&&(this.da=setTimeout(()=>{this.da=null,this.Qt().Ya()},0)),i.Ie(),t.unshift(i)),t}jn(){const e=[];this.Ka()||e.push(this._a),e.push(this.Yh,this.dr);const t=this.oa.map(i=>i.wr());return e.push(...t),_s(this.fa,Ss,"normal",e),e}Ga(){const e=this.Yh.Ga?.()??null;if(e===null)return null;const t=[];this.Ka()||t.push(this._a),t.push(...e.Za),_s(this.fa,Ss,"normal",t);const i=[];i.push(...e.qa,this.dr);const n=this.oa.map(a=>a.wr());return i.push(...n),{Za:t,qa:i}}Xa(){return this.Ja(Ss,"bottom")}Qa(e){return this.Ja(em,e)}tl(e){return this.Ja(tm,e)}il(e,t){return this.fa.map(i=>i.Qs(e,t)).filter(i=>i!==null)}cn(){return[this.pr,...this.oa.map(e=>e.Mr())]}qn(e,t){if(t!==this.hn&&!this.Ka())return[];const i=[...this.mn];for(const n of this.oa)i.push(n.gr());return this.fa.forEach(n=>{i.push(...n.qn())}),i}dn(){const e=[];return this.fa.forEach(t=>{e.push(...t.dn())}),e}la(e,t){if(this.yn.autoscaleInfoProvider!==void 0){const i=this.yn.autoscaleInfoProvider(()=>{const n=this.nl(e,t);return n===null?null:n.sr()});return Qs.er(i)}return this.nl(e,t)}Kh(){const e=this.yn.priceFormat;return e.base??1/e.minMove}sl(){return this.el}Nn(){this.Yh.Pt();for(const e of this.mn)e.Pt();for(const e of this.oa)e.Pt();this.dr.Pt(),this._a.Pt(),this.ua?.Pt(),this.fa.forEach(e=>e.Nn())}Ft(){return P(super.Ft())}At(e){if(!((this.wa==="Line"||this.wa==="Area"||this.wa==="Baseline")&&this.yn.crosshairMarkerVisible))return null;const t=this.qt.Mh(e);return t===null?null:{Mt:t.Wt[3],ft:this.rl(),Ht:this.hl(),Ot:this.al(),zt:this.ll(e)}}He(){return this.yn.title}It(){return this.yn.visible}ol(e){this.fa.push(new Zu(e,this))}_l(e){this.fa=this.fa.filter(t=>t.Qh()!==e)}ul(){if(this.wa==="Custom")return e=>this.Yh.Ha(e)}cl(){if(this.wa==="Custom")return e=>this.Yh.dl(e)}fl(){return this.qt.Lh()}Ka(){return!ui(this.Ft().pl())}nl(e,t){if(!rs(e)||!rs(t)||this.qt.Zi())return null;const i=this.wa==="Line"||this.wa==="Area"||this.wa==="Baseline"||this.wa==="Histogram"?[3]:[2,1],n=this.qt.Eh(e,t,i);let a=n!==null?new ye(n.Uh,n.$h):null,o=null;if(this.bh()==="Histogram"){const l=this.yn.base,c=new ye(l,l);a=a!==null?a.Ss(c):c}return this.fa.forEach(l=>{const c=l.la(e,t);if(c?.priceRange){const d=new ye(c.priceRange.minValue,c.priceRange.maxValue);a=a!==null?a.Ss(d):d}c?.margins&&(o=c.margins)}),new Qs(a,o)}rl(){switch(this.wa){case"Line":case"Area":case"Baseline":return this.yn.crosshairMarkerRadius}return 0}hl(){switch(this.wa){case"Line":case"Area":case"Baseline":{const e=this.yn.crosshairMarkerBorderColor;if(e.length!==0)return e}}return null}al(){switch(this.wa){case"Line":case"Area":case"Baseline":return this.yn.crosshairMarkerBorderWidth}return 0}ll(e){switch(this.wa){case"Line":case"Area":case"Baseline":{const t=this.yn.crosshairMarkerBackgroundColor;if(t.length!==0)return t}}return this.Sa().Sh(e).sh}Ma(){switch(this.yn.priceFormat.type){case"custom":{const e=this.yn.priceFormat.formatter;this.el={format:e,formatTickmarks:this.yn.priceFormat.tickmarksFormatter??(t=>t.map(e))};break}case"volume":this.el=new Mu(this.yn.priceFormat.precision);break;case"percent":this.el=new ro(this.yn.priceFormat.precision);break;default:{const e=Math.pow(10,this.yn.priceFormat.precision);this.el=new mi(e,this.yn.priceFormat.minMove*e)}}this.hn!==null&&this.hn.vl()}Ja(e,t){const i=[];return _s(this.fa,e,t,i),i}Wa(){const{ml:e,wl:t,Ml:i}=this.gl();return this.pa.Sr(e,t,i)}gl(){const e=this.Qt().Et(),t=e.ml(),i=window.devicePixelRatio||1,n=e.N().conflationThresholdFactor;return{ml:t,wl:i,Ml:this.yn.conflationThresholdFactor??n??1}}bl(e){const t=this.qt.Bh();let i;if(this.wa==="Custom"&&this.ma!==null){const a=this.ul();if(!a)throw new Error($u);i=this.pa.Cr(t,e,this.ma,!0,o=>a(o))}else i=this.pa.Cr(t,e);const n=Ri();return n.ht(i),n}$a(e){const t=this.bl(e);this.va.set(e,t)}Da(e){if(this.wa==="Custom"&&(this.ma===null||!this.ul()))return;this.va.clear();const t=this.Qt().Et().Sl();for(const i of t){const n=()=>{this.xl(i)},a=typeof window=="object"&&window||typeof self=="object"&&self;a?.yl?.Cl?a.yl.Cl(()=>{n()},{se:e}):Promise.resolve().then(()=>n())}}xl(e){if(this.va.has(e)||this.qt.Bh().length===0)return;const t=this.bl(e);this.va.set(e,t)}}const im=[3],rm=[0,1,2,3];class nm{constructor(e){this.yn=e}Pl(e,t,i){let n=e;if(this.yn.mode===0)return n;const a=i.kn(),o=a.Lt();if(o===null)return n;const l=a.Nt(e,o),c=i.kl().filter(h=>h instanceof pi).reduce((h,u)=>{if(i.Gs(u)||!u.It())return h;const m=u.Ft(),x=u.Un();if(m.Zi()||!x.ze(t))return h;const b=x.Mh(t);if(b===null)return h;const f=Ye(u.Lt()),g=this.yn.mode===3?rm:im;return h.concat(g.map(p=>m.Nt(b.Wt[p],f.Wt)))},[]);if(c.length===0)return n;c.sort((h,u)=>Math.abs(h-l)-Math.abs(u-l));const d=c[0];return n=a.Tn(d,o),n}}function kt(s,e,t){return Math.min(Math.max(s,e),t)}function ks(s,e,t){return e-s<=t}class am extends Ue{constructor(){super(...arguments),this.qt=null}ht(e){this.qt=e}et({context:e,bitmapSize:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(this.qt===null)return;const a=Math.max(1,Math.floor(i));e.lineWidth=a,function(o,l){o.save(),o.lineWidth%2&&o.translate(.5,.5),l(),o.restore()}(e,()=>{const o=P(this.qt);if(o.Tl){e.strokeStyle=o.Rl,et(e,o.Dl),e.beginPath();for(const l of o.Il){const c=Math.round(l.Vl*i);e.moveTo(c,-a),e.lineTo(c,t.height+a)}e.stroke()}if(o.Bl){e.strokeStyle=o.El,et(e,o.Al),e.beginPath();for(const l of o.Ll){const c=Math.round(l.Vl*n);e.moveTo(-a,c),e.lineTo(t.width+a,c)}e.stroke()}})}}class om{constructor(e){this.Xt=new am,this.xt=!0,this.yt=e}Pt(){this.xt=!0}Tt(){if(this.xt){const e=this.yt.Qt().N().grid,t={Bl:e.horzLines.visible,Tl:e.vertLines.visible,El:e.horzLines.color,Rl:e.vertLines.color,Al:e.horzLines.style,Dl:e.vertLines.style,Ll:this.yt.kn().zl(),Il:(this.yt.Qt().Et().zl()||[]).map(i=>({Vl:i.coord}))};this.Xt.ht(t),this.xt=!1}return this.Xt}}class lm{constructor(e){this.Yh=new om(e)}wr(){return this.Yh}}const Pi={Ol:4,Nl:1e-4};function Nt(s,e){const t=100*(s-e)/e;return e<0?-t:t}function cm(s,e){const t=Nt(s.Je(),e),i=Nt(s.Qe(),e);return new ye(t,i)}function Yt(s,e){const t=100*(s-e)/e+100;return e<0?-t:t}function dm(s,e){const t=Yt(s.Je(),e),i=Yt(s.Qe(),e);return new ye(t,i)}function Js(s,e){const t=Math.abs(s);if(t<1e-15)return 0;const i=Math.log10(t+e.Nl)+e.Ol;return s<0?-i:i}function Jt(s,e){const t=Math.abs(s);if(t<1e-15)return 0;const i=Math.pow(10,t-e.Ol)-e.Nl;return s<0?-i:i}function Ht(s,e){if(s===null)return null;const t=Js(s.Je(),e),i=Js(s.Qe(),e);return new ye(t,i)}function jt(s,e){if(s===null)return null;const t=Jt(s.Je(),e),i=Jt(s.Qe(),e);return new ye(t,i)}function Li(s){if(s===null)return Pi;const e=Math.abs(s.Qe()-s.Je());if(e>=1||e<1e-15)return Pi;const t=Math.ceil(Math.abs(Math.log10(e))),i=Pi.Ol+t;return{Ol:i,Nl:1/Math.pow(10,i)}}class Ai{constructor(e,t){if(this.Fl=e,this.Wl=t,function(i){if(i<0)return!1;if(i>1e18)return!0;for(let n=i;n>1;n/=10)if(n%10!=0)return!1;return!0}(this.Fl))this.Hl=[2,2.5,2];else{this.Hl=[];for(let i=this.Fl;i!==1;){if(i%2==0)this.Hl.push(2),i/=2;else{if(i%5!=0)throw new Error("unexpected base");this.Hl.push(2,2.5),i/=5}if(this.Hl.length>100)throw new Error("something wrong with base")}}}Ul(e,t,i){const n=this.Fl===0?0:1/this.Fl;let a=Math.pow(10,Math.max(0,Math.ceil(Math.log10(e-t)))),o=0,l=this.Wl[0];for(;;){const u=ks(a,n,1e-14)&&a>n+1e-14,m=ks(a,i*l,1e-14),x=ks(a,1,1e-14);if(!(u&&m&&x))break;a/=l,l=this.Wl[++o%this.Wl.length]}if(a<=n+1e-14&&(a=n),a=Math.max(1,a),this.Hl.length>0&&(c=a,d=1,h=1e-14,Math.abs(c-d)n+1e-14;)a/=l,l=this.Hl[++o%this.Hl.length];var c,d,h;return a}}class yn{constructor(e,t,i,n){this.$l=[],this.Ki=e,this.Fl=t,this.jl=i,this.ql=n}Ul(e,t){if(eb.no),x=this.Ki.so(m);for(let b=0;b=n?1:-1;let u=null,m=0;for(let x=i-d;x>n;x-=t){const b=this.ql(x,e,!0);u!==null&&Math.abs(b-u)o||(m0&&l[0].Vl-c.Vl0&&d.Vl-l[l.length-1].VlP(e.ln())-P(t.ln()))}var wn;(function(s){s[s.Normal=0]="Normal",s[s.Logarithmic=1]="Logarithmic",s[s.Percentage=2]="Percentage",s[s.IndexedTo100=3]="IndexedTo100"})(wn||(wn={}));const Nn=new ro,jn=new mi(100,1);class hm{constructor(e,t,i,n,a){this.oo=0,this._o=null,this.rr=null,this.uo=null,this.co={do:!1,fo:null},this.po=!1,this.vo=0,this.mo=0,this.wo=new ce,this.Mo=new ce,this.bo=[],this.So=null,this.xo=null,this.Co=null,this.yo=null,this.Po=null,this.el=jn,this.ko=Li(null),this.To=e,this.yn=t,this.Ro=i,this.Do=n,this.Io=a,this.Vo=new yn(this,100,this.Bo.bind(this),this.Eo.bind(this))}pl(){return this.To}N(){return this.yn}vr(e){if(Me(this.yn,e),this.vl(),e.mode!==void 0&&this.Ao({_e:e.mode}),e.scaleMargins!==void 0){const t=_e(e.scaleMargins.top),i=_e(e.scaleMargins.bottom);if(t<0||t>1)throw new Error(`Invalid top margin - expect value between 0 and 1, given=${t}`);if(i<0||i>1)throw new Error(`Invalid bottom margin - expect value between 0 and 1, given=${i}`);if(t+i>1)throw new Error(`Invalid margins - sum of margins must be less than 1, given=${t+i}`);this.Lo(),this.Co=null}}zo(){return this.yn.autoScale}Oo(){return this.po}ho(){return this.yn.mode===1}je(){return this.yn.mode===2}No(){return this.yn.mode===3}lo(){return this.ko}_e(){return{hs:this.yn.autoScale,Fo:this.yn.invertScale,_e:this.yn.mode}}Ao(e){const t=this._e();let i=null;e.hs!==void 0&&(this.yn.autoScale=e.hs),e._e!==void 0&&(this.yn.mode=e._e,e._e!==2&&e._e!==3||(this.yn.autoScale=!0),this.co.do=!1),t._e===1&&e._e!==t._e&&(function(a,o){if(a===null)return!1;const l=Jt(a.Je(),o),c=Jt(a.Qe(),o);return isFinite(l)&&isFinite(c)}(this.rr,this.ko)?(i=jt(this.rr,this.ko),i!==null&&this.Wo(i)):this.yn.autoScale=!0),e._e===1&&e._e!==t._e&&(i=Ht(this.rr,this.ko),i!==null&&this.Wo(i));const n=t._e!==this.yn.mode;n&&(t._e===2||this.je())&&this.vl(),n&&(t._e===3||this.No())&&this.vl(),e.Fo!==void 0&&t.Fo!==e.Fo&&(this.yn.invertScale=e.Fo,this.Ho()),this.Mo.p(t,this._e())}Uo(){return this.Mo}P(){return this.Ro.fontSize}$t(){return this.oo}$o(e){this.oo!==e&&(this.oo=e,this.Lo(),this.Co=null)}jo(){if(this._o)return this._o;const e=this.$t()-this.qo()-this.Yo();return this._o=e,e}ar(){return this.Ko(),this.rr}Wo(e,t){const i=this.rr;(t||i===null&&e!==null||i!==null&&!i.Ze(e))&&(this.Co=null,this.rr=e)}Go(e){this.Wo(e),this.Zo(e!==null)}Zi(){return this.Ko(),this.oo===0||!this.rr||this.rr.Zi()}Xo(e){return this.Fo()?e:this.$t()-1-e}Nt(e,t){return this.je()?e=Nt(e,t):this.No()&&(e=Yt(e,t)),this.Eo(e,t)}Jo(e,t,i){this.Ko();const n=this.Yo(),a=P(this.ar()),o=a.Je(),l=a.Qe(),c=this.jo()-1,d=this.Fo(),h=c/(l-o),u=i===void 0?0:i.from,m=i===void 0?e.length:i.to,x=this.Qo();for(let b=u;be.Nn())}Xl(){return this.yn.ensureEdgeTickMarksVisible&&this.zo()}Ql(){return this.P()/2}vl(){this.Co=null;let e=1/0;this.So=null;for(const i of this.bo)i.ln()Js(e,this.ko):null}C_(e,t,i){return t===void 0?(i===void 0&&(i=this.sl()),i.format(e)):t(e)}y_(e,t,i){return t===void 0?(i===void 0&&(i=this.sl()),i.formatTickmarks(e)):t(e)}cr(e,t){return this.C_(e,this.Do.priceFormatter,t)}M_(e,t){const i=this.Do.priceFormatter;return this.y_(e,this.Do.tickmarksPriceFormatter??(i?n=>n.map(i):void 0),t)}m_(e,t){return this.C_(e,this.Do.percentageFormatter,t)}w_(e,t){const i=this.Do.percentageFormatter;return this.y_(e,this.Do.tickmarksPercentageFormatter??(i?n=>n.map(i):void 0),t)}}function _n(s){return s instanceof pi}class er{constructor(e,t){this.bo=[],this.P_=new Map,this.oo=0,this.k_=0,this.T_=1,this.xo=null,this.R_=null,this.D_=!1,this.I_=new ce,this.fa=[],this.ia=e,this.sn=t,this.V_=new lm(this);const i=t.N();this.B_=this.E_("left",i.leftPriceScale),this.A_=this.E_("right",i.rightPriceScale),this.B_.Uo().i(this.L_.bind(this,this.B_),this),this.A_.Uo().i(this.L_.bind(this,this.A_),this),this.z_(i)}z_(e){if(e.leftPriceScale&&this.B_.vr(e.leftPriceScale),e.rightPriceScale&&this.A_.vr(e.rightPriceScale),e.localization&&(this.B_.vl(),this.A_.vl()),e.overlayPriceScales){const t=Array.from(this.P_.values());for(const i of t){const n=P(i[0].Ft());n.vr(e.overlayPriceScales),e.localization&&n.vl()}}}O_(e){switch(e){case"left":return this.B_;case"right":return this.A_}return this.P_.has(e)?_e(this.P_.get(e))[0].Ft():null}m(){this.Qt().N_().u(this),this.B_.Uo().u(this),this.A_.Uo().u(this),this.bo.forEach(e=>{e.m&&e.m()}),this.fa=this.fa.filter(e=>{const t=e.Qh();return t.detached&&t.detached(),!1}),this.I_.p()}F_(){return this.T_}W_(e){this.T_=e}Qt(){return this.sn}nn(){return this.k_}$t(){return this.oo}H_(e){this.k_=e,this.U_()}$o(e){this.oo=e,this.B_.$o(e),this.A_.$o(e),this.bo.forEach(t=>{if(this.Gs(t)){const i=t.Ft();i!==null&&i.$o(e)}}),this.U_()}j_(e){this.D_=e}q_(){return this.D_}Y_(){return this.bo.filter(_n)}kl(){return this.bo}Gs(e){const t=e.Ft();return t===null||this.B_!==t&&this.A_!==t}h_(e,t,i){this.K_(e,t,i?e.ln():this.bo.length)}l_(e,t){const i=this.bo.indexOf(e);pe(i!==-1,"removeDataSource: invalid data source"),this.bo.splice(i,1),t||this.bo.forEach((o,l)=>o._n(l));const n=P(e.Ft()).pl();if(this.P_.has(n)){const o=_e(this.P_.get(n)),l=o.indexOf(e);l!==-1&&(o.splice(l,1),o.length===0&&this.P_.delete(n))}const a=e.Ft();a&&a.kl().indexOf(e)>=0&&(a.l_(e),this.G_(a)),this.Z_()}Xs(e){return e===this.B_?"left":e===this.A_?"right":"overlay"}X_(){return this.B_}J_(){return this.A_}Q_(e,t){e.u_(t)}tu(e,t){e.c_(t),this.U_()}iu(e){e.d_()}nu(e,t){e.f_(t)}su(e,t){e.p_(t),this.U_()}eu(e){e.v_()}U_(){this.bo.forEach(e=>{e.Nn()})}kn(){const[e,t]=this.ru();let i=null;return e.N().visible&&e.kl().length!==0?i=e:t.N().visible&&t.kl().length!==0?i=t:this.bo.length!==0&&(i=this.bo[0].Ft()),i===null&&(i=this.Zs()??e),i}Zs(){const[e,t]=this.ru();return e.N().visible?e:t.N().visible?t:null}G_(e){e!==null&&e.zo()&&this.hu(e)}au(e){const t=this.ia.Ee();e.Ao({hs:!0}),t!==null&&e.b_(t),this.U_()}lu(){this.hu(this.B_),this.hu(this.A_)}ou(){this.G_(this.B_),this.G_(this.A_),this.bo.forEach(e=>{this.Gs(e)&&this.G_(e.Ft())}),this.U_(),this.sn.mr()}Dt(){return this.xo===null&&(this.xo=co(this.bo)),this.xo}_u(){const e=this.Dt(),t=this.sn.cu()?.uu,i=this.sn.N().hoveredSeriesOnTop,n=this.R_;if(n!==null&&n.Kh===e&&n.du===t&&n.fu===i)return n.pu;const a=function(o,l,c){if(!c)return o;const d=o.indexOf(l);if(d===-1||d===o.length-1)return o;const h=[];for(let u=0;un._n(a)),this.Z_();for(const n of[this.B_,this.A_])n.a_(),n.vl();this.sn.mr()}Vt(){return this.Dt().filter(_n)}mu(){return this.I_}wu(){return this.V_}ol(e){this.fa.push(new Qu(e))}_l(e){this.fa=this.fa.filter(t=>t.Qh()!==e),e.detached&&e.detached(),this.sn.mr()}Mu(){return this.fa}il(e,t){return this.fa.map(i=>i.Qs(e,t)).filter(i=>i!==null)}hu(e){const t=e.g_();if(t&&t.length>0&&!this.ia.Zi()){const i=this.ia.Ee();i!==null&&e.b_(i)}e.Nn()}K_(e,t,i){let n=this.O_(t);if(n===null&&(n=this.E_(t,this.sn.N().overlayPriceScales)),this.bo.splice(i,0,e),!ui(t)){const a=this.P_.get(t)||[];a.push(e),this.P_.set(t,a)}e._n(i),n.h_(e),e.un(n),this.G_(n),this.Z_()}Z_(){this.xo=null,this.R_=null}ru(){return this.sn.N().defaultVisiblePriceScaleId==="left"?[this.B_,this.A_]:[this.A_,this.B_]}L_(e,t,i){t._e!==i._e&&this.hu(e)}E_(e,t){const i={visible:!0,autoScale:!0,...$e(t)},n=new hm(e,i,this.sn.N().layout,this.sn.N().localization,this.sn.Xi());return n.$o(this.$t()),n}}function tr(s,e){return e===null||s.se===2&&e.se!==2||(e.se!==2||s.se===2)&&s.ne!==e.ne&&s.ne= left"),this.Ru=e,this.Du=t}Na(){return this.Ru}bi(){return this.Du}Iu(){return this.Du-this.Ru+1}ze(e){return this.Ru<=e&&e<=this.Du}Ze(e){return this.Ru===e.Na()&&this.Du===e.bi()}}function Sn(s,e){return s===null||e===null?s===e:s.Ze(e)}class xm{constructor(){this.Vu=new Map,this.Ls=null,this.Bu=!1}Eu(e){this.Bu=e,this.Ls=null}Au(e,t){this.Lu(t),this.Ls=null;for(let i=t;i{e<=i[0].index?t.push(n):i.splice(mt(i,e,a=>a.index!t||i.has(o.index);for(const o of Array.from(this.Vu.keys()).sort((l,c)=>c-l)){if(!this.Vu.get(o))continue;const l=n;n=[];const c=l.length;let d=0;const h=_e(this.Vu.get(o)),u=h.length;let m=1/0,x=-1/0;for(let b=0;b=e&&g-x>=e&&a(f))n.push(f),x=g;else if(this.Bu)return l}for(;de.weight?s:e}class gm{constructor(e,t,i,n){this.k_=0,this.qu=null,this.Yu=[],this.Po=null,this.yo=null,this.Ku=new xm,this.Gu=new Map,this.Zu=Mt.ju(),this.Xu=!0,this.Ju=new ce,this.Qu=new ce,this.tc=new ce,this.nc=null,this.sc=null,this.ec=new Map,this.rc=-1,this.hc=[],this.ac=1,this.yn=t,this.Do=i,this.lc=t.rightOffset,this.oc=t.barSpacing,this.sn=e,this._c(t),this.Pu=n,this.uc(),this.Ku.Eu(t.uniformDistribution),this.cc(),this.dc()}N(){return this.yn}fc(e){Me(this.Do,e),this.vc(),this.uc()}vr(e,t){Me(this.yn,e),this.yn.fixLeftEdge&&this.mc(),this.yn.fixRightEdge&&this.wc(),e.barSpacing!==void 0&&this.sn.Ms(e.barSpacing),e.rightOffset!==void 0&&this.sn.gs(e.rightOffset),this._c(e),e.minBarSpacing===void 0&&e.maxBarSpacing===void 0||this.sn.Ms(e.barSpacing??this.oc),e.ignoreWhitespaceIndices!==void 0&&e.ignoreWhitespaceIndices!==this.yn.ignoreWhitespaceIndices&&this.dc(),this.vc(),this.uc(),e.enableConflation===void 0&&e.conflationThresholdFactor===void 0||this.cc(),this.tc.p()}Rn(e){return this.Yu[e]?.time??null}en(e){return this.Yu[e]??null}Mc(e,t){if(this.Yu.length<1)return null;if(this.Pu.key(e)>this.Pu.key(this.Yu[this.Yu.length-1].time))return t?this.Yu.length-1:null;const i=mt(this.Yu,this.Pu.key(e),(n,a)=>this.Pu.key(n.time)0}Ee(){return this.bc(),this.Zu.Uu()}Sc(){return this.bc(),this.Zu.$u()}xc(){const e=this.Ee();if(e===null)return null;const t={from:e.Na(),to:e.bi()};return this.Cc(t)}Cc(e){const t=Math.round(e.from),i=Math.round(e.to),n=P(this.yc()),a=P(this.Pc());return{from:P(this.en(Math.max(n,t))),to:P(this.en(Math.min(a,i)))}}kc(e){return{from:P(this.Mc(e.from,!0)),to:P(this.Mc(e.to,!0))}}nn(){return this.k_}H_(e){if(!isFinite(e)||e<=0||this.k_===e)return;const t=this.Sc(),i=this.k_;if(this.k_=e,this.Xu=!0,this.yn.lockVisibleTimeRangeOnResize&&i!==0){const n=this.oc*e/i;this.oc=n}if(this.yn.fixLeftEdge&&t!==null&&t.Na()<=0){const n=i-e;this.lc-=Math.round(n/this.oc)+1,this.Xu=!0}this.Tc(),this.Rc()}jt(e){if(this.Zi()||!rs(e))return 0;const t=this.Dc()+this.lc-e;return this.k_-(t+.5)*this.oc-1}Ic(e,t){const i=this.Dc(),n=t===void 0?0:t.from,a=t===void 0?e.length:t.to;for(let o=n;ot/2&&!h?f.needAlignCoordinate=!1:f.needAlignCoordinate=u&&b.index<=c||m&&b.index>=d,x++}return this.hc.length=x,this.sc=this.hc,this.hc}Wc(){let e;this.Xu=!0,this.Ms(this.yn.barSpacing),e=this.yn.rightOffsetPixels!==void 0?this.yn.rightOffsetPixels/this.ml():this.yn.rightOffset,this.gs(e)}Hc(e){this.Xu=!0,this.qu=e,this.Rc(),this.mc()}Uc(e,t){const i=this.Bc(e),n=this.ml(),a=n+t*(n/10);this.Ms(a),this.yn.rightBarStaysOnScroll||this.gs(this.Oc()+(i-this.Bc(e)))}u_(e){this.Po&&this.v_(),this.yo===null&&this.nc===null&&(this.Zi()||(this.yo=e,this.$c()))}c_(e){if(this.nc===null)return;const t=kt(this.k_-e,0,this.k_),i=kt(this.k_-P(this.yo),0,this.k_);t!==0&&i!==0&&this.Ms(this.nc.ml*t/i)}d_(){this.yo!==null&&(this.yo=null,this.jc())}f_(e){this.Po===null&&this.nc===null&&(this.Zi()||(this.Po=e,this.$c()))}p_(e){if(this.Po===null)return;const t=(this.Po-e)/this.ml();this.lc=P(this.nc).Oc+t,this.Xu=!0,this.Rc()}v_(){this.Po!==null&&(this.Po=null,this.jc())}qc(){this.Yc(this.yn.rightOffset)}Yc(e,t=400){if(!isFinite(e))throw new RangeError("offset is required and must be finite number");if(!isFinite(t)||t<=0)throw new RangeError("animationDuration (optional) must be finite positive number");const i=this.lc,n=performance.now();this.sn.ps({Kc:a=>(a-n)/t>=1,Gc:a=>{const o=(a-n)/t;return o>=1?e:i+(e-i)*o}})}Pt(e,t){this.Xu=!0,this.Yu=e,this.Ku.Au(e,t),this.Rc()}Zc(){return this.Ju}Xc(){return this.Qu}Jc(){return this.tc}Dc(){return this.qu||0}Qc(e,t){const i=e.Iu(),n=t&&this.yn.rightOffsetPixels||0;this.zc((this.k_-n)/i),this.lc=e.bi()-this.Dc(),t&&(this.lc=n?n/this.ml():this.yn.rightOffset),this.Rc(),this.Xu=!0,this.sn.Lc(),this.sn.mr()}td(){const e=this.yc(),t=this.Pc();if(e===null||t===null)return;const i=!this.yn.rightOffsetPixels&&this.yn.rightOffset||0;this.Qc(new Xt(e,t+i),!0)}nd(e){const t=new Xt(e.from,e.to);this.Qc(t)}rn(e){return this.Do.timeFormatter!==void 0?this.Do.timeFormatter(e.originalTime):this.Pu.formatHorzItem(e.time)}dc(){if(!this.yn.ignoreWhitespaceIndices)return;this.ec.clear();const e=this.sn.Jn();for(const t of e)for(const i of t.fl())this.ec.set(i,!0);this.rc++}sd(){return this.ac}Sl(){const e=1/(window.devicePixelRatio||1),t=this.yn.minBarSpacing;if(t>=e)return[1];const i=[1];let n=2;for(;n<=512;)t0?this.yn.maxBarSpacing:.5*this.k_}ad(){return this.yn.fixLeftEdge&&this.yn.fixRightEdge&&this.Yu.length!==0?this.k_/this.Yu.length:this.yn.minBarSpacing}cc(){if(!this.yn.enableConflation)return void(this.ac=1);const e=1/(window.devicePixelRatio||1)*(this.yn.conflationThresholdFactor??1);if(this.oc>=e)return void(this.ac=1);const t=e/this.oc,i=Math.pow(2,Math.floor(Math.log2(t)));this.ac=Math.min(i,512)}Rc(){const e=this.od();e!==null&&this.lct&&(this.lc=t,this.Xu=!0)}od(){const e=this.yc(),t=this.qu;return e===null||t===null?null:e-t-1+(this.yn.fixLeftEdge?this.k_/this.oc:Math.min(2,this.Yu.length))}_d(){return this.yn.fixRightEdge?0:this.k_/this.oc-Math.min(2,this.Yu.length)}$c(){this.nc={ml:this.ml(),Oc:this.Oc()}}jc(){this.nc=null}Fc(e){let t=this.Gu.get(e.weight);return t===void 0&&(t=new fm(i=>this.ud(i),this.Pu),this.Gu.set(e.weight,t)),t.ku(e)}ud(e){return this.Pu.formatTickmark(e,this.Do)}hd(e){const t=this.Zu;this.Zu=e,Sn(t.Uu(),this.Zu.Uu())||this.Ju.p(),Sn(t.$u(),this.Zu.$u())||this.Qu.p(),this.rd()}rd(){this.sc=null}vc(){this.rd(),this.Gu.clear()}uc(){this.Pu.updateFormatter(this.Do)}mc(){if(!this.yn.fixLeftEdge)return;const e=this.yc();if(e===null)return;const t=this.Ee();if(t===null)return;const i=t.Na()-e;if(i<0){const n=this.lc-i-1;this.gs(n)}this.Tc()}wc(){this.Rc(),this.Tc()}Ec(e){return!this.yn.ignoreWhitespaceIndices||this.ec.get(e)||!1}Ac(e){const t=function*(n){const a=Math.round(n),o=ai)break}return e}_c(e){if(e.rightOffsetPixels!==void 0){const t=e.rightOffsetPixels/(e.barSpacing||this.oc);this.sn.gs(t)}}}var kn,Mn,Cn,At,En;(function(s){s[s.OnTouchEnd=0]="OnTouchEnd",s[s.OnNextTap=1]="OnNextTap"})(kn||(kn={}));class vm{constructor(e,t,i){this.dd=[],this.fd=[],this.pd=null,this.k_=0,this.vd=null,this.md=new ce,this.wd=new ce,this.Md=null,this.gd=e,this.yn=t,this.Pu=i,this.Io=new pu(this.yn.layout.colorParsers),this.bd=new mu(this),this.ia=new gm(this,t.timeScale,this.yn.localization,i),this.Ct=new ku(this,t.crosshair),this.Sd=new nm(t.crosshair),t.addDefaultPane&&(this.xd(0),this.dd[0].W_(2)),this.Cd=this.yd(0),this.Pd=this.yd(1)}ka(){this.kd(me.ys())}mr(){this.kd(me.Cs())}Ya(){this.kd(new me(1))}Ta(e){const t=this.Td(e);this.kd(t)}cu(){return this.vd}Rd(e){if(this.vd?.uu===e?.uu&&this.vd?.bu?.te===e?.bu?.te&&this.vd?.bu?.ie===e?.bu?.ie&&this.vd?.gu===e?.gu&&this.vd?.ee===e?.ee)return;const t=this.vd;this.vd=e,t!==null&&this.Ta(t.uu),e!==null&&e.uu!==t?.uu&&this.Ta(e.uu)}N(){return this.yn}vr(e){Me(this.yn,e),this.dd.forEach(t=>t.z_(e)),e.timeScale!==void 0&&this.ia.vr(e.timeScale),e.localization!==void 0&&this.ia.fc(e.localization),(e.leftPriceScale||e.rightPriceScale)&&this.md.p(),this.Cd=this.yd(0),this.Pd=this.yd(1),this.ka()}Dd(e,t,i=0){const n=this.dd[i];if(n===void 0)return;if(e==="left")return Me(this.yn,{leftPriceScale:t}),n.z_({leftPriceScale:t}),this.md.p(),void this.ka();if(e==="right")return Me(this.yn,{rightPriceScale:t}),n.z_({rightPriceScale:t}),this.md.p(),void this.ka();const a=this.Id(e,i);a!==null&&(a.Ft.vr(t),this.md.p())}Id(e,t){const i=this.dd[t];if(i===void 0)return null;const n=i.O_(e);return n!==null?{Kn:i,Ft:n}:null}Et(){return this.ia}Gn(){return this.dd}Vd(){return this.Ct}Bd(){return this.wd}Ed(e,t){e.$o(t),this.Lc()}H_(e){this.k_=e,this.ia.H_(this.k_),this.dd.forEach(t=>t.H_(e)),this.Lc()}Ad(e){this.dd.length!==1&&(pe(e>=0&&e=0&&eu+m.F_(),0),a=this.dd.reduce((u,m)=>u+m.$t(),0),o=a-30*(this.dd.length-1);t=Math.min(o,Math.max(30,t));const l=n/a,c=i.$t();i.W_(t*l);let d=t-c,h=this.dd.length-1;for(const u of this.dd)if(u!==i){const m=Math.min(o,Math.max(30,u.$t()-d/h));d-=u.$t()-m,h-=1;const x=m*l;u.W_(x)}this.ka()}zd(e,t){pe(e>=0&&e=0&&t=0&&e=0&&te.It())),this.pd}Pa(){this.pd=null}Kd(e,t,i,n,a){this.Ct.In(e,t);let o=NaN,l=this.ia.Vc(e,!0);const c=this.ia.Ee();c!==null&&(l=Math.min(Math.max(c.Na(),l),c.bi())),l=this.Ct.Fn(l);const d=n.kn(),h=d.Lt();if(h!==null&&(o=d.Tn(t,h)),o=this.Sd.Pl(o,l,n),this.Ct.An(l,o,n),this.Ya(),!a){const u=uo(n,e,t);this.Rd(u&&{uu:u.uu,bu:u.bu,gu:u.gu||null,ee:u.ee}),this.wd.p(this.Ct.Bt(),{x:e,y:t},i)}}Gd(e,t,i){const n=i.kn(),a=n.Lt(),o=n.Nt(e,P(a)),l=this.ia.Mc(t,!0),c=this.ia.jt(P(l));this.Kd(c,o,null,i,!0)}Zd(e){this.Vd().zn(),this.Ya(),e||this.wd.p(null,null,null)}Ra(){const e=this.Ct.Kn();if(e!==null){const t=this.Ct.Bn(),i=this.Ct.En();this.Kd(t,i,null,e)}this.Ct.Nn()}Xd(e,t,i){const n=this.ia.Rn(0);t!==void 0&&i!==void 0&&this.ia.Pt(t,i);const a=this.ia.Rn(0),o=this.ia.Dc(),l=this.ia.Ee();if(l!==null&&n!==null&&a!==null){const c=l.ze(o),d=this.Pu.key(n)>this.Pu.key(a),h=e!==null&&e>o&&!d,u=this.ia.N().allowShiftVisibleRangeOnWhitespaceReplacement,m=c&&(i!==void 0||u)&&this.ia.N().shiftVisibleRangeOnNewBar;if(h&&!m){const x=e-o;this.ia.gs(this.ia.Oc()-x)}}this.ia.Hc(e)}Ba(e){e!==null&&e.ou()}Ks(e){if(function(i){return i instanceof er}(e))return e;const t=this.dd.find(i=>i.Dt().includes(e));return t===void 0?null:t}Lc(){this.dd.forEach(e=>e.ou()),this.Ra()}m(){this.dd.forEach(e=>e.m()),this.dd.length=0,this.yn.localization.priceFormatter=void 0,this.yn.localization.percentageFormatter=void 0,this.yn.localization.timeFormatter=void 0}Jd(){return this.bd}Js(){return this.bd.N()}N_(){return this.md}Qd(e,t){const i=this.xd(t);this.tf(e,i),this.fd.push(e),this.Pa(),this.fd.length===1?this.ka():this.mr()}if(e){const t=this.Ks(e),i=this.fd.indexOf(e);pe(i!==-1,"Series not found");const n=P(t);this.fd.splice(i,1),n.l_(e),e.m&&e.m(),this.Pa(),this.ia.dc(),this.nf(n)}ya(e,t){const i=P(this.Ks(e));i.l_(e,!0),i.h_(e,t,!0)}td(){const e=me.Cs();e.us(),this.kd(e)}sf(e){const t=me.Cs();t.fs(e),this.kd(t)}ws(){const e=me.Cs();e.ws(),this.kd(e)}Ms(e){const t=me.Cs();t.Ms(e),this.kd(t)}gs(e){const t=me.Cs();t.gs(e),this.kd(t)}ps(e){const t=me.Cs();t.ps(e),this.kd(t)}cs(){const e=me.Cs();e.cs(),this.kd(e)}ef(){const e=this.yn.defaultVisiblePriceScaleId,t=this.yn.leftPriceScale.visible;return t!==this.yn.rightPriceScale.visible?t?"left":"right":e}rf(e,t){if(pe(t>=0,"Index should be greater or equal to 0"),t===this.hf(e))return;const i=P(this.Ks(e));i.l_(e);const n=this.xd(t);this.tf(e,n);let a=!1;i.kl().length===0&&(a=this.nf(i)),a||this.ka()}af(){return this.Pd}$(){return this.Cd}Ut(e){const t=this.Pd,i=this.Cd;if(t===i)return t;if(e=Math.max(0,Math.min(100,Math.round(100*e))),this.Md===null||this.Md.ah!==i||this.Md.oh!==t)this.Md={ah:i,oh:t,lf:new Map};else{const a=this.Md.lf.get(e);if(a!==void 0)return a}const n=this.Io.tt(i,t,e/100);return this.Md.lf.set(e,n),n}_f(e){return this.dd.indexOf(e)}Xi(){return this.Io}uf(){return this.cf()}cf(e){const t=new er(this.ia,this);this.dd.push(t);const i=e??this.dd.length-1,n=me.ys();return n.es(i,{rs:0,hs:!0}),this.kd(n),t}xd(e){return pe(e>=0,"Index should be greater or equal to 0"),(e=Math.min(this.dd.length,e))t.Y_().includes(e))}Nd(e,t){const i=new me(t);if(e!==null){const n=this.dd.indexOf(e);i.es(n,{rs:t})}return i}Td(e,t){return t===void 0&&(t=2),this.Nd(this.Ks(e),t)}kd(e){this.gd&&this.gd(e),this.dd.forEach(t=>t.wu().wr().Pt())}tf(e,t){const i=e.N().priceScaleId,n=i!==void 0?i:this.ef();t.h_(e,n),ui(n)||e.vr(e.N())}yd(e){const t=this.yn.layout;return t.background.type==="gradient"?e===0?t.background.topColor:t.background.bottomColor:t.background.color}nf(e){return!e.q_()&&e.kl().length===0&&this.dd.length>1&&(this.dd.splice(this._f(e),1),this.ka(),!0)}}function mo(s){if(s>=1)return 0;let e=0;for(;e<8;e++){const t=Math.round(s);if(Math.abs(t-s)<1e-8)return e;s*=10}return e}function sr(s){return!Pt(s)&&!fs(s)}function po(s){return Pt(s)}(function(s){s[s.Disabled=0]="Disabled",s[s.Continuous=1]="Continuous",s[s.OnDataUpdate=2]="OnDataUpdate"})(Mn||(Mn={})),function(s){s[s.LastBar=0]="LastBar",s[s.LastVisible=1]="LastVisible"}(Cn||(Cn={})),function(s){s.Solid="solid",s.VerticalGradient="gradient"}(At||(At={})),function(s){s[s.Year=0]="Year",s[s.Month=1]="Month",s[s.DayOfMonth=2]="DayOfMonth",s[s.Time=3]="Time",s[s.TimeWithSeconds=4]="TimeWithSeconds"}(En||(En={}));const Tn=s=>s.getUTCFullYear();function ym(s,e,t){return e.replace(/yyyy/g,(i=>De(Tn(i),4))(s)).replace(/yy/g,(i=>De(Tn(i)%100,2))(s)).replace(/MMMM/g,((i,n)=>new Date(i.getUTCFullYear(),i.getUTCMonth(),1).toLocaleString(n,{month:"long"}))(s,t)).replace(/MMM/g,((i,n)=>new Date(i.getUTCFullYear(),i.getUTCMonth(),1).toLocaleString(n,{month:"short"}))(s,t)).replace(/MM/g,(i=>De((n=>n.getUTCMonth()+1)(i),2))(s)).replace(/dd/g,(i=>De((n=>n.getUTCDate())(i),2))(s))}class fo{constructor(e="yyyy-MM-dd",t="default"){this.df=e,this.ff=t}ku(e){return ym(e,this.df,this.ff)}}class wm{constructor(e){this.pf=e||"%h:%m:%s"}ku(e){return this.pf.replace("%h",De(e.getUTCHours(),2)).replace("%m",De(e.getUTCMinutes(),2)).replace("%s",De(e.getUTCSeconds(),2))}}const Nm={vf:"yyyy-MM-dd",mf:"%h:%m:%s",wf:" ",Mf:"default"};class jm{constructor(e={}){const t={...Nm,...e};this.gf=new fo(t.vf,t.Mf),this.bf=new wm(t.mf),this.Sf=t.wf}ku(e){return`${this.gf.ku(e)}${this.Sf}${this.bf.ku(e)}`}}function Cs(s){return 60*s*60*1e3}function Oi(s){return 60*s*1e3}const Es=[{xf:(Rn=1,1e3*Rn),Cf:10},{xf:Oi(1),Cf:20},{xf:Oi(5),Cf:21},{xf:Oi(30),Cf:22},{xf:Cs(1),Cf:30},{xf:Cs(3),Cf:31},{xf:Cs(6),Cf:32},{xf:Cs(12),Cf:33}];var Rn;function Pn(s,e){if(s.getUTCFullYear()!==e.getUTCFullYear())return 70;if(s.getUTCMonth()!==e.getUTCMonth())return 60;if(s.getUTCDate()!==e.getUTCDate())return 50;for(let t=Es.length-1;t>=0;--t)if(Math.floor(e.getTime()/Es[t].xf)!==Math.floor(s.getTime()/Es[t].xf))return Es[t].Cf;return 0}function zi(s){let e=s;if(fs(s)&&(e=jr(s)),!sr(e))throw new Error("time must be of type BusinessDay");const t=new Date(Date.UTC(e.year,e.month-1,e.day,0,0,0,0));return{yf:Math.round(t.getTime()/1e3),Pf:e}}function Ln(s){if(!po(s))throw new Error("time must be of type isUTCTimestamp");return{yf:s}}function jr(s){const e=new Date(s);if(isNaN(e.getTime()))throw new Error(`Invalid date string=${s}, expected format=yyyy-mm-dd`);return{day:e.getUTCDate(),month:e.getUTCMonth()+1,year:e.getUTCFullYear()}}function An(s){fs(s.time)&&(s.time=jr(s.time))}class On{options(){return this.yn}setOptions(e){this.yn=e,this.updateFormatter(e.localization)}preprocessData(e){Array.isArray(e)?function(t){t.forEach(An)}(e):An(e)}createConverterToInternalObj(e){return P(function(t){return t.length===0?null:sr(t[0].time)||fs(t[0].time)?zi:Ln}(e))}key(e){return typeof e=="object"&&"yf"in e?e.yf:this.key(this.convertHorzItemToInternal(e))}cacheKey(e){const t=e;return t.Pf===void 0?new Date(1e3*t.yf).getTime():new Date(Date.UTC(t.Pf.year,t.Pf.month-1,t.Pf.day)).getTime()}convertHorzItemToInternal(e){return po(t=e)?Ln(t):sr(t)?zi(t):zi(jr(t));var t}updateFormatter(e){if(!this.yn)return;const t=e.dateFormat;this.yn.timeScale.timeVisible?this.kf=new jm({vf:t,mf:this.yn.timeScale.secondsVisible?"%h:%m:%s":"%h:%m",wf:" ",Mf:e.locale}):this.kf=new fo(t,e.locale)}formatHorzItem(e){const t=e;return this.kf.ku(new Date(1e3*t.yf))}formatTickmark(e,t){const i=function(a,o,l){switch(a){case 0:case 10:return o?l?4:3:2;case 20:case 21:case 22:case 30:case 31:case 32:case 33:return o?3:2;case 50:return 2;case 60:return 1;case 70:return 0}}(e.weight,this.yn.timeScale.timeVisible,this.yn.timeScale.secondsVisible),n=this.yn.timeScale;if(n.tickMarkFormatter!==void 0){const a=n.tickMarkFormatter(e.originalTime,i,t.locale);if(a!==null)return a}return function(a,o,l){const c={};switch(o){case 0:c.year="numeric";break;case 1:c.month="short";break;case 2:c.day="numeric";break;case 3:c.hour12=!1,c.hour="2-digit",c.minute="2-digit";break;case 4:c.hour12=!1,c.hour="2-digit",c.minute="2-digit",c.second="2-digit"}const d=a.Pf===void 0?new Date(1e3*a.yf):new Date(Date.UTC(a.Pf.year,a.Pf.month-1,a.Pf.day));return new Date(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),d.getUTCMilliseconds()).toLocaleString(l,c)}(e.time,i,t.locale)}maxTickMarkWeight(e){let t=e.reduce(bm,e[0]).weight;return t>30&&t<50&&(t=30),t}fillWeightsForPoints(e,t){(function(i,n=0){if(i.length===0)return;let a=n===0?null:i[n-1].time.yf,o=a!==null?new Date(1e3*a):null,l=0;for(let c=n;c1){const c=Math.ceil(l/(i.length-1)),d=new Date(1e3*(i[0].time.yf-c));i[0].timeWeight=Pn(new Date(1e3*i[0].time.yf),d)}})(e,t)}static Tf(e){return Me({localization:{dateFormat:"dd MMM 'yy"}},e??{})}}const Ot=typeof window<"u";function zn(){return!!Ot&&window.navigator.userAgent.toLowerCase().indexOf("firefox")>-1}function Ii(){return!!Ot&&/iPhone|iPad|iPod/.test(window.navigator.platform)}function _m(s,e){switch(s){case"custom":return e!==void 0?"custom-object":"series";case"price-line":return"custom-price-line";case"marker":return"series-marker";case"primitive":return"primitive";default:return"series"}}function ir(s){return s+s%2}function Sm(s){Ot&&window.chrome!==void 0&&s.addEventListener("mousedown",e=>{if(e.button===1)return e.preventDefault(),!1})}class fi{constructor(e,t,i){this.Rf=0,this.Df=null,this.If={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY},this.Vf=0,this.Bf=null,this.Ef={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY},this.Af=null,this.Lf=!1,this.zf=null,this.Of=null,this.Nf=!1,this.Ff=!1,this.Wf=!1,this.Hf=null,this.Uf=null,this.$f=null,this.jf=null,this.qf=null,this.Yf=null,this.Kf=null,this.Gf=0,this.Zf=!1,this.Xf=!1,this.Jf=!1,this.Qf=0,this.tp=null,this.ip=!Ii(),this.np=n=>{this.sp(n)},this.ep=n=>{if(this.rp(n)){const a=this.hp(n);if(++this.Vf,this.Bf&&this.Vf>1){const{ap:o}=this.lp(Le(n),this.Ef);o<30&&!this.Wf&&this.op(a,this.up._p),this.cp()}}else{const a=this.hp(n);if(++this.Rf,this.Df&&this.Rf>1){const{ap:o}=this.lp(Le(n),this.If);o<5&&!this.Ff&&this.dp(a,this.up.fp),this.pp()}}},this.vp=e,this.up=t,this.yn=i,this.mp()}m(){this.Hf!==null&&(this.Hf(),this.Hf=null),this.Uf!==null&&(this.Uf(),this.Uf=null),this.jf!==null&&(this.jf(),this.jf=null),this.qf!==null&&(this.qf(),this.qf=null),this.Yf!==null&&(this.Yf(),this.Yf=null),this.$f!==null&&(this.$f(),this.$f=null),this.wp(),this.pp()}Mp(e){this.jf&&this.jf();const t=this.gp.bind(this);if(this.jf=()=>{this.vp.removeEventListener("mousemove",t)},this.vp.addEventListener("mousemove",t),this.rp(e))return;const i=this.hp(e);this.dp(i,this.up.bp),this.ip=!0}pp(){this.Df!==null&&clearTimeout(this.Df),this.Rf=0,this.Df=null,this.If={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY}}cp(){this.Bf!==null&&clearTimeout(this.Bf),this.Vf=0,this.Bf=null,this.Ef={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY}}gp(e){if(this.Jf||this.Of!==null||this.rp(e))return;const t=this.hp(e);this.dp(t,this.up.Sp),this.ip=!0}xp(e){const t=$i(e.changedTouches,P(this.tp));if(t===null||(this.Qf=Ts(e),this.Kf!==null)||this.Xf)return;this.Zf=!0;const i=this.lp(Le(t),P(this.Of)),{Cp:n,yp:a,ap:o}=i;if(this.Nf||!(o<5)){if(!this.Nf){const l=.5*n,c=a>=l&&!this.yn.Pp(),d=l>a&&!this.yn.kp();c||d||(this.Xf=!0),this.Nf=!0,this.Wf=!0,this.wp(),this.cp()}if(!this.Xf){const l=this.hp(e,t);this.op(l,this.up.Tp),vt(e)}}}Rp(e){if(e.button!==0)return;const t=this.lp(Le(e),P(this.zf)),{ap:i}=t;if(i>=5&&(this.Ff=!0,this.pp()),this.Ff){const n=this.hp(e);this.dp(n,this.up.Dp)}}lp(e,t){const i=Math.abs(t._t-e._t),n=Math.abs(t.ut-e.ut);return{Cp:i,yp:n,ap:i+n}}Ip(e){let t=$i(e.changedTouches,P(this.tp));if(t===null&&e.touches.length===0&&(t=e.changedTouches[0]),t===null)return;this.tp=null,this.Qf=Ts(e),this.wp(),this.Of=null,this.Yf&&(this.Yf(),this.Yf=null);const i=this.hp(e,t);if(this.op(i,this.up.Vp),++this.Vf,this.Bf&&this.Vf>1){const{ap:n}=this.lp(Le(t),this.Ef);n<30&&!this.Wf&&this.op(i,this.up._p),this.cp()}else this.Wf||(this.op(i,this.up.Bp),this.up.Bp&&vt(e));this.Vf===0&&vt(e),e.touches.length===0&&this.Lf&&(this.Lf=!1,vt(e))}sp(e){if(e.button!==0)return;const t=this.hp(e);if(this.zf=null,this.Jf=!1,this.qf&&(this.qf(),this.qf=null),zn()&&this.vp.ownerDocument.documentElement.removeEventListener("mouseleave",this.np),!this.rp(e))if(this.dp(t,this.up.Ep),++this.Rf,this.Df&&this.Rf>1){const{ap:i}=this.lp(Le(e),this.If);i<5&&!this.Ff&&this.dp(t,this.up.fp),this.pp()}else this.Ff||this.dp(t,this.up.Ap)}wp(){this.Af!==null&&(clearTimeout(this.Af),this.Af=null)}Lp(e){if(this.tp!==null)return;const t=e.changedTouches[0];this.tp=t.identifier,this.Qf=Ts(e);const i=this.vp.ownerDocument.documentElement;this.Wf=!1,this.Nf=!1,this.Xf=!1,this.Of=Le(t),this.Yf&&(this.Yf(),this.Yf=null);{const a=this.xp.bind(this),o=this.Ip.bind(this);this.Yf=()=>{i.removeEventListener("touchmove",a),i.removeEventListener("touchend",o)},i.addEventListener("touchmove",a,{passive:!1}),i.addEventListener("touchend",o,{passive:!1}),this.wp(),this.Af=setTimeout(this.zp.bind(this,e),240)}const n=this.hp(e,t);this.op(n,this.up.Op),this.Bf||(this.Vf=0,this.Bf=setTimeout(this.cp.bind(this),500),this.Ef=Le(t))}Np(e){if(e.button!==0)return;const t=this.vp.ownerDocument.documentElement;zn()&&t.addEventListener("mouseleave",this.np),this.Ff=!1,this.zf=Le(e),this.qf&&(this.qf(),this.qf=null);{const n=this.Rp.bind(this),a=this.sp.bind(this);this.qf=()=>{t.removeEventListener("mousemove",n),t.removeEventListener("mouseup",a)},t.addEventListener("mousemove",n),t.addEventListener("mouseup",a)}if(this.Jf=!0,this.rp(e))return;const i=this.hp(e);this.dp(i,this.up.Fp),this.Df||(this.Rf=0,this.Df=setTimeout(this.pp.bind(this),500),this.If=Le(e))}mp(){this.vp.addEventListener("mouseenter",this.Mp.bind(this)),this.vp.addEventListener("touchcancel",this.wp.bind(this));{const e=this.vp.ownerDocument,t=i=>{this.up.Wp&&(i.composed&&this.vp.contains(i.composedPath()[0])||i.target&&this.vp.contains(i.target)||this.up.Wp())};this.Uf=()=>{e.removeEventListener("touchstart",t)},this.Hf=()=>{e.removeEventListener("mousedown",t)},e.addEventListener("mousedown",t),e.addEventListener("touchstart",t,{passive:!0})}Ii()&&(this.$f=()=>{this.vp.removeEventListener("dblclick",this.ep)},this.vp.addEventListener("dblclick",this.ep)),this.vp.addEventListener("mouseleave",this.Hp.bind(this)),this.vp.addEventListener("touchstart",this.Lp.bind(this),{passive:!0}),Sm(this.vp),this.vp.addEventListener("mousedown",this.Np.bind(this)),this.Up(),this.vp.addEventListener("touchmove",()=>{},{passive:!1})}Up(){this.up.$p===void 0&&this.up.jp===void 0&&this.up.qp===void 0||(this.vp.addEventListener("touchstart",e=>this.Yp(e.touches),{passive:!0}),this.vp.addEventListener("touchmove",e=>{if(e.touches.length===2&&this.Kf!==null&&this.up.jp!==void 0){const t=In(e.touches[0],e.touches[1])/this.Gf;this.up.jp(this.Kf,t),vt(e)}},{passive:!1}),this.vp.addEventListener("touchend",e=>{this.Yp(e.touches)}))}Yp(e){e.length===1&&(this.Zf=!1),e.length!==2||this.Zf||this.Lf?this.Kp():this.Gp(e)}Gp(e){const t=this.vp.getBoundingClientRect()||{left:0,top:0};this.Kf={_t:(e[0].clientX-t.left+(e[1].clientX-t.left))/2,ut:(e[0].clientY-t.top+(e[1].clientY-t.top))/2},this.Gf=In(e[0],e[1]),this.up.$p!==void 0&&this.up.$p(),this.wp()}Kp(){this.Kf!==null&&(this.Kf=null,this.up.qp!==void 0&&this.up.qp())}Hp(e){if(this.jf&&this.jf(),this.rp(e)||!this.ip)return;const t=this.hp(e);this.dp(t,this.up.Zp),this.ip=!Ii()}zp(e){const t=$i(e.touches,P(this.tp));if(t===null)return;const i=this.hp(e,t);this.op(i,this.up.Xp),this.Wf=!0,this.Lf=!0}rp(e){return e.sourceCapabilities&&e.sourceCapabilities.firesTouchEvents!==void 0?e.sourceCapabilities.firesTouchEvents:Ts(e){e.type!=="touchstart"&&vt(e)}}}}function In(s,e){const t=s.clientX-e.clientX,i=s.clientY-e.clientY;return Math.sqrt(t*t+i*i)}function vt(s){s.cancelable&&s.preventDefault()}function Le(s){return{_t:s.pageX,ut:s.pageY}}function Ts(s){return s.timeStamp||performance.now()}function $i(s,e){for(let t=0;t!1,kp:()=>!0}),this.nv={Mv:i,wv:e}}cv(){this.uv.style.background=this.hv.N().layout.panes.separatorColor}gv(e){this.nv!==null&&(this.nv.Mv.style.backgroundColor=this.hv.N().layout.panes.separatorHoverColor)}bv(e){this.nv!==null&&this.rv===null&&(this.nv.Mv.style.backgroundColor="")}Sv(e){if(this.nv===null)return;const t=this.av.yv().F_()+this.ov.yv().F_(),i=t/(this.av.pv().height+this.ov.pv().height),n=30*i;t<=2*n||(this.rv={Pv:e.pageY,kv:this.av.yv().F_(),Tv:t-n,Rv:t,Dv:i,Iv:n},this.nv.wv.style.display="block")}xv(e){const t=this.rv;if(t===null)return;const i=(e.pageY-t.Pv)*t.Dv,n=kt(t.kv+i,t.Iv,t.Tv);this.av.yv().W_(n),this.ov.yv().W_(t.Rv-n),this.hv.Qt().ka()}Cv(e){this.rv!==null&&this.nv!==null&&(this.rv=null,this.nv.wv.style.display="none")}}function Di(s,e){return s.Vv-e.Vv}function Bi(s,e,t){const i=(s.Vv-e.Vv)/(s.wt-e.wt);return Math.sign(i)*Math.min(Math.abs(i),t)}class Mm{constructor(e,t,i,n){this.Bv=null,this.Ev=null,this.Av=null,this.Lv=null,this.zv=null,this.Ov=0,this.Nv=0,this.Fv=e,this.Wv=t,this.Hv=i,this.Ps=n}Uv(e,t){if(this.Bv!==null){if(this.Bv.wt===t)return void(this.Bv.Vv=e);if(Math.abs(this.Bv.Vv-e)50)return;let i=0;const n=Bi(this.Bv,this.Ev,this.Wv),a=Di(this.Bv,this.Ev),o=[n],l=[a];if(i+=a,this.Av!==null){const d=Bi(this.Ev,this.Av,this.Wv);if(Math.sign(d)===Math.sign(n)){const h=Di(this.Ev,this.Av);if(o.push(d),l.push(h),i+=h,this.Lv!==null){const u=Bi(this.Av,this.Lv,this.Wv);if(Math.sign(u)===Math.sign(n)){const m=Di(this.Av,this.Lv);o.push(u),l.push(m),i+=m}}}}let c=0;for(let d=0;d160?"dark":"light"}Qv(){return this.Gv.N().layout.attributionLogo}im(){const e=new URL(location.href);return e.hostname?"&utm_source="+e.hostname+e.pathname:""}Zv(){this.Jv()&&(this.Xv(),this.vn=this.Qv(),this.vn&&(this.Yv=this.tm(),this.qv=document.createElement("style"),this.qv.innerText="a#tv-attr-logo{--fill:#131722;--stroke:#fff;position:absolute;left:10px;bottom:10px;height:19px;width:35px;margin:0;padding:0;border:0;z-index:3;}a#tv-attr-logo[data-dark]{--fill:#D1D4DC;--stroke:#131722;}",this.jv=document.createElement("a"),this.jv.href=`https://www.tradingview.com/?utm_medium=lwc-link&utm_campaign=lwc-chart${this.im()}`,this.jv.title="Charting by TradingView",this.jv.id="tv-attr-logo",this.jv.target="_blank",this.jv.innerHTML='',this.jv.toggleAttribute("data-dark",this.Yv==="dark"),this.Kv.appendChild(this.qv),this.Kv.appendChild(this.jv)))}}function pt(s,e){const t=P(s.ownerDocument).createElement("canvas");s.appendChild(t);const i=cu(t,{options:{allowResizeObserver:!0},transform:(n,a)=>({width:Math.max(n.width,a.width),height:Math.max(n.height,a.height)})});return i.resizeCanvasElement(e),i}function ft(s){s.width=1,s.height=1,s.getContext("2d")?.clearRect(0,0,1,1)}function $s(s,e,t,i){s.qh&&s.qh(e,t,i)}function Kt(s,e,t,i){s.st(e,t,i)}function rr(s,e,t,i){xo(s(t,i),e,i)}function xo(s,e,t){for(const i of s){const n=i.Tt(t);n!==null&&e(n)}}function Fi(s,e){return t=>function(i){return i.Ft!==void 0}(t)?(t.Ft()?.pl()??"")!==e?[]:t.Qa?.(s)??[]:[]}function $n(s,e,t,i){if(!s.length)return;let n=0;const a=s[0].$t(i,!0);let o=e===1?t/2-(s[0].Hi()-a/2):s[0].Hi()-a/2-t/2;o=Math.max(0,o);for(let l=1;lm-h:ut)&&o>0){const f=e===1?-1-b:b-t,g=Math.min(f,o);for(let p=n;p{this.lm||this.yt._m().Qt().mr()},this.um=()=>{this.lm||this.yt._m().Qt().mr()},this.yt=e,this.yn=t,this.Ro=t.layout,this.bd=i,this.dm=n==="left",this.fm=Fi("normal",n),this.pm=Fi("top",n),this.vm=Fi("bottom",n),this.uv=document.createElement("div"),this.uv.style.height="100%",this.uv.style.overflow="hidden",this.uv.style.width="25px",this.uv.style.left="0",this.uv.style.position="relative",this.wm=pt(this.uv,re({width:16,height:16})),this.wm.subscribeSuggestedBitmapSizeChanged(this.om);const a=this.wm.canvasElement;a.style.position="absolute",a.style.zIndex="1",a.style.left="0",a.style.top="0",this.Mm=pt(this.uv,re({width:16,height:16})),this.Mm.subscribeSuggestedBitmapSizeChanged(this.um);const o=this.Mm.canvasElement;o.style.position="absolute",o.style.zIndex="2",o.style.left="0",o.style.top="0";const l={Fp:this.Sv.bind(this),Op:this.Sv.bind(this),Dp:this.xv.bind(this),Tp:this.xv.bind(this),Wp:this.gm.bind(this),Ep:this.Cv.bind(this),Vp:this.Cv.bind(this),fp:this.bm.bind(this),_p:this.bm.bind(this),bp:this.Sm.bind(this),Zp:this.bv.bind(this)};this.sv=new fi(this.Mm.canvasElement,l,{Pp:()=>!this.yn.handleScroll.vertTouchDrag,kp:()=>!0})}m(){this.sv.m(),this.Mm.unsubscribeSuggestedBitmapSizeChanged(this.um),ft(this.Mm.canvasElement),this.Mm.dispose(),this.wm.unsubscribeSuggestedBitmapSizeChanged(this.om),ft(this.wm.canvasElement),this.wm.dispose(),this.Ki!==null&&this.Ki.__().u(this),this.Ki=null}fv(){return this.uv}P(){return this.Ro.fontSize}xm(){const e=this.bd.N();return this.hm!==e.k&&(this.rm.Os(),this.hm=e.k),e}Cm(){if(this.Ki===null)return 0;let e=0;const t=this.xm(),i=P(this.wm.canvasElement.getContext("2d",{colorSpace:this.yt._m().N().layout.colorSpace}));i.save();const n=this.Ki.zl();i.font=this.ym(),n.length>0&&(e=Math.max(this.rm.Ii(i,n[0].eo),this.rm.Ii(i,n[n.length-1].eo)));const a=this.Pm();for(let d=a.length;d--;){const h=this.rm.Ii(i,a[d].ri());h>e&&(e=h)}const o=this.Ki.Lt();if(o!==null&&this.nm!==null&&(l=this.yn.crosshair).mode!==2&&l.horzLine.visible&&l.horzLine.labelVisible){const d=this.Ki.Tn(1,o),h=this.Ki.Tn(this.nm.height-2,o);e=Math.max(e,this.rm.Ii(i,this.Ki.Ji(Math.floor(Math.min(d,h))+.11111111111111,o)),this.rm.Ii(i,this.Ki.Ji(Math.ceil(Math.max(d,h))-.11111111111111,o)))}var l;i.restore();const c=e||34;return ir(Math.ceil(t.S+t.C+t.V+t.B+5+c))}km(e){this.nm!==null&&nt(this.nm,e)||(this.nm=e,this.lm=!0,this.wm.resizeCanvasElement(e),this.Mm.resizeCanvasElement(e),this.lm=!1,this.uv.style.width=`${e.width}px`,this.uv.style.height=`${e.height}px`)}Tm(){return P(this.nm).width}un(e){this.Ki!==e&&(this.Ki!==null&&this.Ki.__().u(this),this.Ki=e,e.__().i(this.wo.bind(this),this))}Ft(){return this.Ki}Os(){const e=this.yt.yv();this.yt._m().Qt().au(e,P(this.Ft()))}Rm(e){if(this.nm===null)return;const t={colorSpace:this.yt._m().N().layout.colorSpace};if(e!==1){this.Dm(),this.wm.applySuggestedBitmapSize();const n=ut(this.wm,t);n!==null&&(n.useBitmapCoordinateSpace(a=>{this.Im(a),this.Vm(a)}),this.yt.Bm(n,this.vm),this.Em(n),this.yt.Bm(n,this.fm),this.Am(n))}this.Mm.applySuggestedBitmapSize();const i=ut(this.Mm,t);i!==null&&(i.useBitmapCoordinateSpace(({context:n,bitmapSize:a})=>{n.clearRect(0,0,a.width,a.height)}),this.Lm(i),this.yt.Bm(i,this.pm))}vv(){return this.wm.bitmapSize}mv(e,t,i,n){const a=this.vv();if(a.width>0&&a.height>0&&(e.drawImage(this.wm.canvasElement,t,i),n)){const o=this.Mm.canvasElement;e.drawImage(o,t,i)}}Pt(){this.Ki?.zl()}Sv(e){if(this.Ki===null||this.Ki.Zi()||!this.yn.handleScale.axisPressedMouseMove.price)return;const t=this.yt._m().Qt(),i=this.yt.yv();this.sm=!0,t.Q_(i,this.Ki,e.localY)}xv(e){if(this.Ki===null||!this.yn.handleScale.axisPressedMouseMove.price)return;const t=this.yt._m().Qt(),i=this.yt.yv(),n=this.Ki;t.tu(i,n,e.localY)}gm(){if(this.Ki===null||!this.yn.handleScale.axisPressedMouseMove.price)return;const e=this.yt._m().Qt(),t=this.yt.yv(),i=this.Ki;this.sm&&(this.sm=!1,e.iu(t,i))}Cv(e){if(this.Ki===null||!this.yn.handleScale.axisPressedMouseMove.price)return;const t=this.yt._m().Qt(),i=this.yt.yv();this.sm=!1,t.iu(i,this.Ki)}bm(e){this.yn.handleScale.axisDoubleClickReset.price&&this.Os()}Sm(e){this.Ki!==null&&(!this.yt._m().Qt().N().handleScale.axisPressedMouseMove.price||this.Ki.je()||this.Ki.No()||this.zm(1))}bv(e){this.zm(0)}Pm(){const e=[],t=this.Ki===null?void 0:this.Ki;return(i=>{for(let n=0;n{o.fillStyle=i.borderColor;const d=Math.max(1,Math.floor(c)),h=Math.floor(.5*c),u=Math.round(n.C*l);o.beginPath();for(const m of t)o.rect(Math.floor(a*l),Math.round(m.Vl*c)-h,u,d);o.fill()}),e.useMediaCoordinateSpace(({context:o})=>{o.font=this.ym(),o.fillStyle=i.textColor??this.Ro.textColor,o.textAlign=this.dm?"right":"left",o.textBaseline="middle";const l=this.dm?Math.round(a-n.V):Math.round(a+n.C+n.V),c=t.map(d=>this.rm.Di(o,d.eo));for(let d=t.length;d--;){const h=t[d];o.fillText(h.eo,l,h.Vl+c[d])}})}Dm(){if(this.nm===null||this.Ki===null)return;let e=this.nm.height/2;const t=[],i=this.Ki.Dt().slice(),n=this.yt.yv(),a=this.xm();this.Ki===n.Zs()&&this.yt.yv().Dt().forEach(c=>{n.Gs(c)&&i.push(c)});const o=this.Ki.kl()[0],l=this.Ki;i.forEach(c=>{const d=c.qn(n,l);d.forEach(h=>{h.$i()&&h.Wi()===null&&(h.Ui(null),t.push(h))}),o===c&&d.length>0&&(e=d[0].Ei())}),this.Ki.N().alignLabels&&this.Om(t,a,e)}Om(e,t,i){if(this.nm===null)return;const n=e.filter(o=>o.Ei()<=i),a=e.filter(o=>o.Ei()>i);n.sort((o,l)=>l.Ei()-o.Ei()),n.length&&a.length&&a.push(n[0]),a.sort((o,l)=>o.Ei()-l.Ei());for(const o of e){const l=Math.floor(o.$t(t)/2),c=o.Ei();c>-l&&cthis.nm.height-l&&c{a.ji()&&a.Tt(P(this.Ki)).st(e,i,this.rm,n)})}Lm(e){if(this.nm===null||this.Ki===null)return;const t=this.yt._m().Qt(),i=[],n=this.yt.yv(),a=t.Vd().qn(n,this.Ki);a.length&&i.push(a);const o=this.xm(),l=this.dm?"right":"left";i.forEach(c=>{c.forEach(d=>{d.Tt(P(this.Ki)).st(e,o,this.rm,l)})})}zm(e){this.uv.style.cursor=e===1?"ns-resize":"default"}wo(){const e=this.Cm();this.am{this.lm||this.Jm===null||this.sn().mr()},this.um=()=>{this.lm||this.Jm===null||this.sn().mr()},this.Gv=e,this.Jm=t,this.Jm.mu().i(this.Qm.bind(this),this,!0),this.tw=document.createElement("td"),this.tw.style.padding="0",this.tw.style.position="relative";const i=document.createElement("div");i.style.width="100%",i.style.height="100%",i.style.position="relative",i.style.overflow="hidden",this.iw=document.createElement("td"),this.iw.style.padding="0",this.nw=document.createElement("td"),this.nw.style.padding="0",this.tw.appendChild(i),this.wm=pt(i,re({width:16,height:16})),this.wm.subscribeSuggestedBitmapSizeChanged(this.om);const n=this.wm.canvasElement;n.style.position="absolute",n.style.zIndex="1",n.style.left="0",n.style.top="0",this.Mm=pt(i,re({width:16,height:16})),this.Mm.subscribeSuggestedBitmapSizeChanged(this.um);const a=this.Mm.canvasElement;a.style.position="absolute",a.style.zIndex="2",a.style.left="0",a.style.top="0",this._v=document.createElement("tr"),this._v.appendChild(this.iw),this._v.appendChild(this.tw),this._v.appendChild(this.nw),this.sw(),this.sv=new fi(this.Mm.canvasElement,this,{Pp:()=>this.Km===null&&!this.Gv.N().handleScroll.vertTouchDrag,kp:()=>this.Km===null&&!this.Gv.N().handleScroll.horzTouchDrag})}m(){this.Nm!==null&&this.Nm.m(),this.Fm!==null&&this.Fm.m(),this.Wm=null,this.Mm.unsubscribeSuggestedBitmapSizeChanged(this.um),ft(this.Mm.canvasElement),this.Mm.dispose(),this.wm.unsubscribeSuggestedBitmapSizeChanged(this.om),ft(this.wm.canvasElement),this.wm.dispose(),this.Jm!==null&&(this.Jm.mu().u(this),this.Jm.m()),this.sv.m()}yv(){return P(this.Jm)}ew(e){this.Jm!==null&&this.Jm.mu().u(this),this.Jm=e,this.Jm!==null&&this.Jm.mu().i(_r.prototype.Qm.bind(this),this,!0),this.sw(),this.Gv.lv().indexOf(this)===this.Gv.lv().length-1?(this.Wm=this.Wm??new Cm(this.tw,this.Gv),this.Wm.Pt()):(this.Wm?.Xv(),this.Wm=null)}_m(){return this.Gv}fv(){return this._v}sw(){if(this.Jm!==null&&(this.rw(),this.sn().Jn().length!==0)){if(this.Nm!==null){const e=this.Jm.X_();this.Nm.un(P(e))}if(this.Fm!==null){const e=this.Jm.J_();this.Fm.un(P(e))}}}hw(){this.Nm!==null&&this.Nm.Pt(),this.Fm!==null&&this.Fm.Pt()}F_(){return this.Jm!==null?this.Jm.F_():0}W_(e){this.Jm&&this.Jm.W_(e)}bp(e){if(!this.Jm)return;this.aw();const t=e.localX,i=e.localY;this.lw(t,i,e)}Fp(e){this.aw(),this.ow(),this.lw(e.localX,e.localY,e)}Sp(e){if(!this.Jm)return;this.aw();const t=e.localX,i=e.localY;this.lw(t,i,e)}Ap(e){this.Jm!==null&&(this.aw(),this.lw(e.localX,e.localY,e),this._w(e))}fp(e){this.Jm!==null&&this.uw(this.jm,e)}_p(e){this.fp(e)}Dp(e){this.aw(),this.cw(e),this.lw(e.localX,e.localY,e)}Ep(e){this.Jm!==null&&(this.aw(),this.Ym=!1,this.dw(e))}Bp(e){this.Jm!==null&&this._w(e)}Xp(e){if(this.Ym=!0,this.Km===null){const t={x:e.localX,y:e.localY};this.fw(t,t,e)}}Zp(e){this.Jm!==null&&(this.aw(),this.Jm.Qt().Rd(null),this.pw())}mw(){return this.$m}ww(){return this.jm}$p(){this.qm=1,this.sn().cs()}jp(e,t){if(!this.Gv.N().handleScale.pinch)return;const i=5*(t-this.qm);this.qm=t,this.sn().Wd(e._t,i)}Op(e){this.Ym=!1,this.Gm=this.Km!==null,this.ow();const t=this.sn().Vd();this.Km!==null&&t.It()&&(this.Zm={x:t.ni(),y:t.si()},this.Km={x:e.localX,y:e.localY})}Tp(e){if(this.Jm===null)return;const t=e.localX,i=e.localY;if(this.Km===null)this.cw(e);else{this.Gm=!1;const n=P(this.Zm),a=n.x+(t-this.Km.x),o=n.y+(i-this.Km.y);this.lw(a,o,e)}}Vp(e){this._m().N().trackingMode.exitMode===0&&(this.Gm=!0),this.Mw(),this.dw(e)}Qs(e,t){const i=this.Jm;return i===null?null:uo(i,e,t)}gw(e,t){P(t==="left"?this.Nm:this.Fm).km(re({width:e,height:this.nm.height}))}pv(){return this.nm}km(e){nt(this.nm,e)||(this.nm=e,this.lm=!0,this.wm.resizeCanvasElement(e),this.Mm.resizeCanvasElement(e),this.lm=!1,this.tw.style.width=e.width+"px",this.tw.style.height=e.height+"px")}bw(){const e=P(this.Jm);e.G_(e.X_()),e.G_(e.J_());for(const t of e.kl())if(e.Gs(t)){const i=t.Ft();i!==null&&e.G_(i),t.Nn()}for(const t of e.Mu())t.Nn()}vv(){return this.wm.bitmapSize}mv(e,t,i,n){const a=this.vv();if(a.width>0&&a.height>0&&(e.drawImage(this.wm.canvasElement,t,i),n)){const o=this.Mm.canvasElement;e!==null&&e.drawImage(o,t,i)}}Rm(e){if(e===0||this.Jm===null)return;e>1&&this.bw(),this.Nm!==null&&this.Nm.Rm(e),this.Fm!==null&&this.Fm.Rm(e);const t={colorSpace:this.Gv.N().layout.colorSpace};if(e!==1){this.wm.applySuggestedBitmapSize();const n=ut(this.wm,t);n!==null&&(n.useBitmapCoordinateSpace(a=>{this.Im(a)}),this.Jm&&(this.Sw(n,Em),this.xw(n),this.Sw(n,Ui),this.Sw(n,Bn)))}this.Mm.applySuggestedBitmapSize();const i=ut(this.Mm,t);i!==null&&(i.useBitmapCoordinateSpace(({context:n,bitmapSize:a})=>{n.clearRect(0,0,a.width,a.height)}),this.Cw(i),this.Sw(i,Tm),this.Sw(i,Bn))}yw(){return this.Nm}Pw(){return this.Fm}Bm(e,t){this.Sw(e,t)}Qm(){this.Jm!==null&&this.Jm.mu().u(this),this.Jm=null}_w(e){this.uw(this.$m,e)}uw(e,t){const i=t.localX,n=t.localY;e.v()&&e.p(this.sn().Et().Vc(i),{x:i,y:n},t)}Im({context:e,bitmapSize:t}){const{width:i,height:n}=t,a=this.sn(),o=a.$(),l=a.af();o===l?di(e,0,0,i,n,l):eo(e,0,0,i,n,o,l)}xw(e){const t=P(this.Jm),i=t.wu().wr().Tt(t);i!==null&&i.st(e,!1)}Cw(e){this.kw(e,Ui,Kt,this.sn().Vd())}Sw(e,t){const i=P(this.Jm),n=t===Ui?this.Tw():null,a=n===null?null:this.Rw(n,i),o=i.Mu();if(a===null||n===null){const d=i._u();return this.Dw(e,t,$s,o,d),void this.Dw(e,t,Kt,o,d)}const l=i.Dt(),c=d=>d===n?a.Za:void 0;this.Dw(e,t,$s,o,l,c),this.Dw(e,t,Kt,o,l,c),this.kw(e,t,$s,n,a.qa),this.kw(e,t,Kt,n,a.qa)}Dw(e,t,i,n,a,o){for(const l of n)this.kw(e,t,i,l);if(o!==void 0)for(const l of a)this.kw(e,t,i,l,o(l));else for(const l of a)this.kw(e,t,i,l)}Tw(){const e=P(this.Jm),t=e.Qt().cu()?.uu;if(!e.Qt().N().hoveredSeriesOnTop||t===void 0)return null;for(const i of e.Dt())if(i===t)return i;return null}Rw(e,t){const i=e.Ga?.(t)??null;return i===null||i.qa.length===0?null:i}kw(e,t,i,n,a){const o=P(this.Jm),l=o.Qt().cu(),c=l!==null&&l.uu===n,d=l!==null&&c&&l.bu!==void 0?l.bu.ie:void 0,h=u=>i(u,e,c,d);a===void 0?rr(t,h,n,o):xo(a,h,o)}rw(){if(this.Jm===null)return;const e=this.Gv,t=this.Jm.X_().N().visible,i=this.Jm.J_().N().visible;t||this.Nm===null||(this.iw.removeChild(this.Nm.fv()),this.Nm.m(),this.Nm=null),i||this.Fm===null||(this.nw.removeChild(this.Fm.fv()),this.Fm.m(),this.Fm=null);const n=e.Qt().Jd();t&&this.Nm===null&&(this.Nm=new Dn(this,e.N(),n,"left"),this.iw.appendChild(this.Nm.fv())),i&&this.Fm===null&&(this.Fm=new Dn(this,e.N(),n,"right"),this.nw.appendChild(this.Fm.fv()))}Iw(e){return e.Jp&&this.Ym||this.Km!==null}lw(e,t,i){e=Math.max(0,Math.min(e,this.nm.width-1)),t=Math.max(0,Math.min(t,this.nm.height-1)),this.sn().Kd(e,t,i,P(this.Jm))}pw(){this.sn().Zd()}Mw(){this.Gm&&(this.Km=null,this.pw())}fw(e,t,i){this.Km=e,this.Gm=!1,this.lw(t.x,t.y,i);const n=this.sn().Vd();this.Zm={x:n.ni(),y:n.si()}}sn(){return this.Gv.Qt()}dw(e){if(!this.Um)return;const t=this.sn(),i=this.yv();if(t.eu(i,i.kn()),this.Hm=null,this.Um=!1,t.jd(),this.Xm!==null){const n=performance.now(),a=t.Et();this.Xm.me(a.Oc(),n),this.Xm.Kc(n)||t.ps(this.Xm)}}aw(){this.Km=null}ow(){if(this.Jm){if(this.sn().cs(),document.activeElement!==document.body&&document.activeElement!==document.documentElement)P(document.activeElement).blur();else{const e=document.getSelection();e!==null&&e.removeAllRanges()}!this.Jm.kn().Zi()&&this.sn().Et().Zi()}}cw(e){if(this.Jm===null)return;const t=this.sn(),i=t.Et();if(i.Zi())return;const n=this.Gv.N(),a=n.handleScroll,o=n.kineticScroll;if((!a.pressedMouseMove||e.Jp)&&(!a.horzTouchDrag&&!a.vertTouchDrag||!e.Jp))return;const l=this.Jm.kn(),c=performance.now();if(this.Hm!==null||this.Iw(e)||(this.Hm={x:e.clientX,y:e.clientY,yf:c,Vw:e.localX,Bw:e.localY}),this.Hm!==null&&!this.Um&&(this.Hm.x!==e.clientX||this.Hm.y!==e.clientY)){if(e.Jp&&o.touch||!e.Jp&&o.mouse){const d=i.ml();this.Xm=new Mm(.2/d,7/d,.997,15/d),this.Xm.Uv(i.Oc(),this.Hm.yf)}else this.Xm=null;l.Zi()||t.nu(this.Jm,l,e.localY),t.Ud(e.localX),this.Um=!0}this.Um&&(l.Zi()||t.su(this.Jm,l,e.localY),t.$d(e.localX),this.Xm!==null&&this.Xm.Uv(i.Oc(),c))}}class Fn{constructor(e,t,i,n,a){this.xt=!0,this.nm=re({width:0,height:0}),this.om=()=>this.Rm(3),this.dm=e==="left",this.bd=i.Jd,this.yn=t,this.Ew=n,this.Aw=a,this.uv=document.createElement("div"),this.uv.style.width="25px",this.uv.style.height="100%",this.uv.style.overflow="hidden",this.wm=pt(this.uv,re({width:16,height:16})),this.wm.subscribeSuggestedBitmapSizeChanged(this.om)}m(){this.wm.unsubscribeSuggestedBitmapSizeChanged(this.om),ft(this.wm.canvasElement),this.wm.dispose()}fv(){return this.uv}pv(){return this.nm}km(e){nt(this.nm,e)||(this.nm=e,this.wm.resizeCanvasElement(e),this.uv.style.width=`${e.width}px`,this.uv.style.height=`${e.height}px`,this.xt=!0)}Rm(e){if(e<3&&!this.xt||this.nm.width===0||this.nm.height===0)return;this.xt=!1,this.wm.applySuggestedBitmapSize();const t=ut(this.wm,{colorSpace:this.yn.layout.colorSpace});t!==null&&t.useBitmapCoordinateSpace(i=>{this.Im(i),this.Vm(i)})}vv(){return this.wm.bitmapSize}mv(e,t,i){const n=this.vv();n.width>0&&n.height>0&&e.drawImage(this.wm.canvasElement,t,i)}Vm({context:e,bitmapSize:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(!this.Ew())return;e.fillStyle=this.yn.timeScale.borderColor;const a=Math.floor(this.bd.N().S*i),o=Math.floor(this.bd.N().S*n),l=this.dm?t.width-a:0;e.fillRect(l,0,a,o)}Im({context:e,bitmapSize:t}){di(e,0,0,t.width,t.height,this.Aw())}}function Sr(s){return e=>e.tl?.(s)??[]}const Rm=Sr("normal"),Pm=Sr("top"),Lm=Sr("bottom");class Am{constructor(e,t){this.Lw=null,this.zw=null,this.M=null,this.Ow=!1,this.nm=re({width:0,height:0}),this.Nw=new ce,this.rm=new Gs(5),this.lm=!1,this.om=()=>{this.lm||this.Gv.Qt().mr()},this.um=()=>{this.lm||this.Gv.Qt().mr()},this.Gv=e,this.Pu=t,this.yn=e.N().layout,this.jv=document.createElement("tr"),this.Fw=document.createElement("td"),this.Fw.style.padding="0",this.Ww=document.createElement("td"),this.Ww.style.padding="0",this.uv=document.createElement("td"),this.uv.style.height="25px",this.uv.style.padding="0",this.Hw=document.createElement("div"),this.Hw.style.width="100%",this.Hw.style.height="100%",this.Hw.style.position="relative",this.Hw.style.overflow="hidden",this.uv.appendChild(this.Hw),this.wm=pt(this.Hw,re({width:16,height:16})),this.wm.subscribeSuggestedBitmapSizeChanged(this.om);const i=this.wm.canvasElement;i.style.position="absolute",i.style.zIndex="1",i.style.left="0",i.style.top="0",this.Mm=pt(this.Hw,re({width:16,height:16})),this.Mm.subscribeSuggestedBitmapSizeChanged(this.um);const n=this.Mm.canvasElement;n.style.position="absolute",n.style.zIndex="2",n.style.left="0",n.style.top="0",this.jv.appendChild(this.Fw),this.jv.appendChild(this.uv),this.jv.appendChild(this.Ww),this.Uw(),this.Gv.Qt().N_().i(this.Uw.bind(this),this),this.sv=new fi(this.Mm.canvasElement,this,{Pp:()=>!0,kp:()=>!this.Gv.N().handleScroll.horzTouchDrag})}m(){this.sv.m(),this.Lw!==null&&this.Lw.m(),this.zw!==null&&this.zw.m(),this.Mm.unsubscribeSuggestedBitmapSizeChanged(this.um),ft(this.Mm.canvasElement),this.Mm.dispose(),this.wm.unsubscribeSuggestedBitmapSizeChanged(this.om),ft(this.wm.canvasElement),this.wm.dispose()}fv(){return this.jv}$w(){return this.Lw}jw(){return this.zw}Fp(e){if(this.Ow)return;this.Ow=!0;const t=this.Gv.Qt();!t.Et().Zi()&&this.Gv.N().handleScale.axisPressedMouseMove.time&&t.Fd(e.localX)}Op(e){this.Fp(e)}Wp(){const e=this.Gv.Qt();!e.Et().Zi()&&this.Ow&&(this.Ow=!1,this.Gv.N().handleScale.axisPressedMouseMove.time&&e.Yd())}Dp(e){const t=this.Gv.Qt();!t.Et().Zi()&&this.Gv.N().handleScale.axisPressedMouseMove.time&&t.qd(e.localX)}Tp(e){this.Dp(e)}Ep(){this.Ow=!1;const e=this.Gv.Qt();e.Et().Zi()&&!this.Gv.N().handleScale.axisPressedMouseMove.time||e.Yd()}Vp(){this.Ep()}fp(){this.Gv.N().handleScale.axisDoubleClickReset.time&&this.Gv.Qt().ws()}_p(){this.fp()}bp(){this.Gv.Qt().N().handleScale.axisPressedMouseMove.time&&this.zm(1)}Zp(){this.zm(0)}pv(){return this.nm}qw(){return this.Nw}Yw(e,t,i){nt(this.nm,e)||(this.nm=e,this.lm=!0,this.wm.resizeCanvasElement(e),this.Mm.resizeCanvasElement(e),this.lm=!1,this.uv.style.width=`${e.width}px`,this.uv.style.height=`${e.height}px`,this.Nw.p(e)),this.Lw!==null&&this.Lw.km(re({width:t,height:e.height})),this.zw!==null&&this.zw.km(re({width:i,height:e.height}))}Kw(){const e=this.Gw();return Math.ceil(e.S+e.C+e.P+e.A+e.I+e.Zw)}Pt(){this.Gv.Qt().Et().zl()}vv(){return this.wm.bitmapSize}mv(e,t,i,n){const a=this.vv();if(a.width>0&&a.height>0&&(e.drawImage(this.wm.canvasElement,t,i),n)){const o=this.Mm.canvasElement;e.drawImage(o,t,i)}}Rm(e){if(e===0)return;const t={colorSpace:this.yn.colorSpace};if(e!==1){this.wm.applySuggestedBitmapSize();const n=ut(this.wm,t);n!==null&&(n.useBitmapCoordinateSpace(a=>{this.Im(a),this.Vm(a),this.Xw(n,Lm)}),this.Em(n),this.Xw(n,Rm)),this.Lw!==null&&this.Lw.Rm(e),this.zw!==null&&this.zw.Rm(e)}this.Mm.applySuggestedBitmapSize();const i=ut(this.Mm,t);i!==null&&(i.useBitmapCoordinateSpace(({context:n,bitmapSize:a})=>{n.clearRect(0,0,a.width,a.height)}),this.Jw([...this.Gv.Qt().Jn(),this.Gv.Qt().Vd()],i),this.Xw(i,Pm))}Xw(e,t){const i=this.Gv.Qt().Jn();for(const n of i)rr(t,a=>$s(a,e,!1,void 0),n,void 0);for(const n of i)rr(t,a=>Kt(a,e,!1,void 0),n,void 0)}Im({context:e,bitmapSize:t}){di(e,0,0,t.width,t.height,this.Gv.Qt().af())}Vm({context:e,bitmapSize:t,verticalPixelRatio:i}){if(this.Gv.N().timeScale.borderVisible){e.fillStyle=this.Qw();const n=Math.max(1,Math.floor(this.Gw().S*i));e.fillRect(0,0,t.width,n)}}Em(e){const t=this.Gv.Qt().Et(),i=t.zl();if(!i||i.length===0)return;const n=this.Pu.maxTickMarkWeight(i),a=this.Gw(),o=t.N();o.borderVisible&&o.ticksVisible&&e.useBitmapCoordinateSpace(({context:l,horizontalPixelRatio:c,verticalPixelRatio:d})=>{l.strokeStyle=this.Qw(),l.fillStyle=this.Qw();const h=Math.max(1,Math.floor(c)),u=Math.floor(.5*c);l.beginPath();const m=Math.round(a.C*d);for(let x=i.length;x--;){const b=Math.round(i[x].coord*c);l.rect(b-u,0,h,m)}l.fill()}),e.useMediaCoordinateSpace(({context:l})=>{const c=a.S+a.C+a.A+a.P/2;l.textAlign="center",l.textBaseline="middle",l.fillStyle=this.H(),l.font=this.ym();for(const d of i)if(d.weight=n){const h=d.needAlignCoordinate?this.tM(l,d.coord,d.label):d.coord;l.fillText(d.label,h,c)}})}tM(e,t,i){const n=this.rm.Ii(e,i),a=n/2,o=Math.floor(t-a)+.5;return o<0?t+=Math.abs(0-o):o+n>this.nm.width&&(t-=Math.abs(this.nm.width-(o+n))),t}Jw(e,t){const i=this.Gw();for(const n of e)for(const a of n.dn())a.Tt().st(t,i)}Qw(){return this.Gv.N().timeScale.borderColor}H(){return this.yn.textColor}F(){return this.yn.fontSize}ym(){return Ks(this.F(),this.yn.fontFamily)}iM(){return Ks(this.F(),this.yn.fontFamily,"bold")}Gw(){this.M===null&&(this.M={S:1,L:NaN,A:NaN,I:NaN,tn:NaN,C:5,P:NaN,k:"",Qi:new Gs,Zw:0});const e=this.M,t=this.ym();if(e.k!==t){const i=this.F();e.P=i,e.k=t,e.A=3*i/12,e.I=3*i/12,e.tn=9*i/12,e.L=0,e.Zw=4*i/12,e.Qi.Os()}return this.M}zm(e){this.uv.style.cursor=e===1?"ew-resize":"default"}Uw(){const e=this.Gv.Qt(),t=e.N();t.leftPriceScale.visible||this.Lw===null||(this.Fw.removeChild(this.Lw.fv()),this.Lw.m(),this.Lw=null),t.rightPriceScale.visible||this.zw===null||(this.Ww.removeChild(this.zw.fv()),this.zw.m(),this.zw=null);const i={Jd:this.Gv.Qt().Jd()},n=()=>t.leftPriceScale.borderVisible&&e.Et().N().borderVisible,a=()=>e.af();t.leftPriceScale.visible&&this.Lw===null&&(this.Lw=new Fn("left",t,i,n,a),this.Fw.appendChild(this.Lw.fv())),t.rightPriceScale.visible&&this.zw===null&&(this.zw=new Fn("right",t,i,n,a),this.Ww.appendChild(this.zw.fv()))}}const Om=!!Ot&&!!navigator.userAgentData&&navigator.userAgentData.brands.some(s=>s.brand.includes("Chromium"))&&!!Ot&&(navigator?.userAgentData?.platform?navigator.userAgentData.platform==="Windows":navigator.userAgent.toLowerCase().indexOf("win")>=0);class zm{constructor(e,t,i){var n;this.nM=[],this.sM=[],this.eM=0,this.oo=0,this.k_=0,this.rM=0,this.hM=0,this.aM=null,this.lM=!1,this.$m=new ce,this.jm=new ce,this.wd=new ce,this.oM=null,this._M=null,this.Kv=e,this.yn=t,this.Pu=i,this.jv=document.createElement("div"),this.jv.classList.add("tv-lightweight-charts"),this.jv.style.overflow="hidden",this.jv.style.direction="ltr",this.jv.style.width="100%",this.jv.style.height="100%",(n=this.jv).style.userSelect="none",n.style.webkitUserSelect="none",n.style.msUserSelect="none",n.style.MozUserSelect="none",n.style.webkitTapHighlightColor="transparent",this.uM=document.createElement("table"),this.uM.setAttribute("cellspacing","0"),this.jv.appendChild(this.uM),this.cM=this.dM.bind(this),qi(this.yn)&&this.fM(!0),this.sn=new vm(this.gd.bind(this),this.yn,i),this.Qt().Bd().i(this.pM.bind(this),this),this.vM=new Am(this,this.Pu),this.uM.appendChild(this.vM.fv());const a=t.autoSize&&this.mM();let o=this.yn.width,l=this.yn.height;if(a||o===0||l===0){const c=e.getBoundingClientRect();o=o||c.width,l=l||c.height}this.wM(o,l),this.MM(),e.appendChild(this.jv),this.gM(),this.sn.Et().Jc().i(this.sn.ka.bind(this.sn),this),this.sn.N_().i(this.sn.ka.bind(this.sn),this)}Qt(){return this.sn}N(){return this.yn}lv(){return this.nM}bM(){return this.vM}m(){this.fM(!1),this.eM!==0&&window.cancelAnimationFrame(this.eM),this.sn.Bd().u(this),this.sn.Et().Jc().u(this),this.sn.N_().u(this),this.sn.m();for(const e of this.nM)this.uM.removeChild(e.fv()),e.mw().u(this),e.ww().u(this),e.m();this.nM=[];for(const e of this.sM)this.SM(e);this.sM=[],P(this.vM).m(),this.jv.parentElement!==null&&this.jv.parentElement.removeChild(this.jv),this.wd.m(),this.$m.m(),this.jm.m(),this.xM()}wM(e,t,i=!1){if(this.oo===t&&this.k_===e)return;const n=function(l){const c=Math.floor(l.width),d=Math.floor(l.height);return re({width:c-c%2,height:d-d%2})}(re({width:e,height:t}));this.oo=n.height,this.k_=n.width;const a=this.oo+"px",o=this.k_+"px";if(this.CM()||(P(this.jv).style.height=a,P(this.jv).style.width=o),this.uM.style.height=a,this.uM.style.width=o,i){this.eM!==0&&(window.cancelAnimationFrame(this.eM),this.eM=0),this.lM=!1;const l=me.ys();this.aM!==null&&(l.Ss(this.aM),this.aM=null),this.yM(l,performance.now())}else this.sn.ka()}Rm(e){e===void 0&&(e=me.ys());for(let t=0;t{e.Pt()})}kM(e){(e.autoSize!==void 0||!this.oM||e.width===void 0&&e.height===void 0)&&(e.autoSize&&!this.oM&&this.mM(),e.autoSize===!1&&this.oM!==null&&this.xM(),e.autoSize||e.width===void 0&&e.height===void 0||this.wM(e.width||this.k_,e.height||this.oo))}RM(e,t){let i=0,n=0;const a=this.nM[0],o=(c,d)=>{let h=0;for(let u=0;u{P(c==="left"?this.vM.$w():this.vM.jw()).mv(P(e),d,h)};if(this.yn.timeScale.visible){const c=this.vM.vv();if(e!==null){let d=0;this.IM()&&(l("left",d,n),d=P(a.yw()).vv().width),this.vM.mv(e,d,n,t),d+=c.width,this.VM()&&l("right",d,n)}n+=c.height}return re({width:i,height:n})}LM(){let e=0,t=0,i=0;for(const g of this.nM)this.IM()&&(t=Math.max(t,P(g.yw()).Cm(),this.yn.leftPriceScale.minimumWidth)),this.VM()&&(i=Math.max(i,P(g.Pw()).Cm(),this.yn.rightPriceScale.minimumWidth)),e+=g.F_();t=ir(t),i=ir(i);const n=this.k_,a=this.oo,o=Math.max(n-t-i,0),l=1*this.sM.length,c=this.yn.timeScale.visible;let d=c?Math.max(this.vM.Kw(),this.yn.timeScale.minimumHeight):0;var h;d=(h=d)+h%2;const u=l+d,m=a{n.hw()}),this.aM?.ls()===3&&(this.aM.Ss(e),this.OM(),this.NM(this.aM),this.FM(this.aM,t),e=this.aM,this.aM=null)),this.Rm(e)}FM(e,t){for(const i of e.bs())this.xs(i,t)}NM(e){const t=this.sn.Gn();for(let i=0;i{if(this.lM=!1,this.eM=0,this.aM!==null){const i=this.aM;this.aM=null,this.yM(i,t);for(const n of i.bs())if(n.ds===5&&!n.Wt.Kc(t)){this.Qt().ps(n.Wt);break}}}))}OM(){this.MM()}SM(e){this.uM.removeChild(e.fv()),e.m()}MM(){const e=this.sn.Gn(),t=e.length,i=this.nM.length;for(let n=t;n0){const o=new km(this,n-1,n);this.sM.push(o),this.uM.insertBefore(o.fv(),this.vM.fv())}this.uM.insertBefore(a.fv(),this.vM.fv())}for(let n=0;n{const u=h.Un().Hn(e);u!==null&&a.set(h,u)});let o;if(e!==null){const h=this.sn.Et().en(e)?.originalTime;h!==void 0&&(o=h)}const l=this.Qt().cu(),c=this.$M(n),d=function(h,u){const m=h!==null&&h.uu instanceof pi?h.uu:void 0,x=h?.bu?.te,b=u!==void 0&&u!==-1?u:void 0;return h===null||h.ee===void 0?{jM:m,qM:x}:{jM:m,qM:x,YM:{ds:h.ee,KM:(f=h.uu,g=h.ee,f instanceof er?"pane-primitive":g==="marker"||g==="primitive"?"series-primitive":"series"),GM:_m(h.ee,x),Y_:m,ZM:x,XM:b}};var f,g}(l,c);return{Qr:o,$n:e??void 0,JM:t??void 0,XM:c!==-1?c:void 0,jM:d.jM,QM:a,qM:d.qM,YM:d.YM,tg:i??void 0}}$M(e){let t=-1;if(e)t=this.nM.indexOf(e);else{const i=this.Qt().Vd().Kn();i!==null&&(t=this.Qt().Gn().indexOf(i))}return t}WM(e,t,i,n){this.$m.p(()=>this.UM(t,i,n,e))}HM(e,t,i,n){this.jm.p(()=>this.UM(t,i,n,e))}pM(e,t,i){this.BM(this.Qt().cu()?.gu??null),this.wd.p(()=>this.UM(e,t,i))}gM(){const e=this.yn.timeScale.visible?"":"none";this.vM.fv().style.display=e}IM(){return this.nM[0].yv().X_().N().visible}VM(){return this.nM[0].yv().J_().N().visible}mM(){return"ResizeObserver"in window&&(this.oM=new ResizeObserver(e=>{const t=e[e.length-1];if(!t)return;const i=t.contentRect.width,n=t.contentRect.height;this.wM(i,n,!0)}),this.oM.observe(this.Kv,{box:"border-box"}),!0)}xM(){this.oM!==null&&this.oM.disconnect(),this.oM=null}}function qi(s){return!!(s.handleScroll.mouseWheel||s.handleScale.mouseWheel)}function Im(s){return s.open===void 0&&s.value===void 0}function $m(s){return function(e){return e.open!==void 0}(s)||function(e){return e.value!==void 0}(s)}function Un(s,e,t,i){const n=t.value,a={$n:e,wt:s,Wt:[n,n,n,n],Qr:i};return t.color!==void 0&&(a.R=t.color),a}function Dm(s,e,t,i){const n=t.value,a={$n:e,wt:s,Wt:[n,n,n,n],Qr:i};return t.lineColor!==void 0&&(a.vt=t.lineColor),t.topColor!==void 0&&(a.ah=t.topColor),t.bottomColor!==void 0&&(a.oh=t.bottomColor),a}function Bm(s,e,t,i){const n=t.value,a={$n:e,wt:s,Wt:[n,n,n,n],Qr:i};return t.topLineColor!==void 0&&(a._h=t.topLineColor),t.bottomLineColor!==void 0&&(a.uh=t.bottomLineColor),t.topFillColor1!==void 0&&(a.dh=t.topFillColor1),t.topFillColor2!==void 0&&(a.fh=t.topFillColor2),t.bottomFillColor1!==void 0&&(a.ph=t.bottomFillColor1),t.bottomFillColor2!==void 0&&(a.mh=t.bottomFillColor2),a}function Fm(s,e,t,i){const n={$n:e,wt:s,Wt:[t.open,t.high,t.low,t.close],Qr:i};return t.color!==void 0&&(n.R=t.color),n}function Um(s,e,t,i){const n={$n:e,wt:s,Wt:[t.open,t.high,t.low,t.close],Qr:i};return t.color!==void 0&&(n.R=t.color),t.borderColor!==void 0&&(n.Ht=t.borderColor),t.wickColor!==void 0&&(n.hh=t.wickColor),n}function qm(s,e,t,i,n){const a=_e(n)(t),o=Math.max(...a),l=Math.min(...a),c=a[a.length-1],d=[c,o,l,c],{time:h,color:u,...m}=t;return{$n:e,wt:s,Wt:d,Qr:i,ue:m,R:u}}function yt(s){return s.Wt!==void 0}function qn(s,e){return e.customValues!==void 0&&(s.ig=e.customValues),s}function st(s){return(e,t,i,n,a,o)=>function(l,c){return c?c(l):Im(l)}(i,o)?qn({wt:e,$n:t,Qr:n},i):qn(s(e,t,i,n,a),i)}function Wn(s){return{Candlestick:st(Um),Bar:st(Fm),Area:st(Dm),Baseline:st(Bm),Histogram:st(Un),Line:st(Un),Custom:st(qm)}[s]}function Hn(s){return{$n:0,ng:new Map,Oa:s}}function Vn(s,e){if(s!==void 0&&s.length!==0)return{sg:e.key(s[0].wt),eg:e.key(s[s.length-1].wt)}}function Kn(s){let e;return s.forEach(t=>{e===void 0&&(e=t.Qr)}),_e(e)}class Wm{constructor(e){this.rg=new Map,this.hg=new Map,this.ag=new Map,this.lg=[],this.Pu=e}m(){this.rg.clear(),this.hg.clear(),this.ag.clear(),this.lg=[]}og(e,t){let i=this.rg.size!==0,n=!1;const a=this.hg.get(e);if(a!==void 0)if(this.hg.size===1)i=!1,n=!0,this.rg.clear();else for(const c of this.lg)c.pointData.ng.delete(e)&&(n=!0);let o=[];if(t.length!==0){const c=t.map(x=>x.time),d=this.Pu.createConverterToInternalObj(t),h=Wn(e.bh()),u=e.ul(),m=e.cl();o=t.map((x,b)=>{const f=d(x.time),g=this.Pu.key(f);let p=this.rg.get(g);p===void 0&&(p=Hn(f),this.rg.set(g,p),n=!0);const v=h(f,p.$n,x,c[b],u,m);return p.ng.set(e,v),v})}i&&this._g(),this.ug(e,o);let l=-1;if(n){const c=[];this.rg.forEach(d=>{c.push({timeWeight:0,time:d.Oa,pointData:d,originalTime:Kn(d.ng)})}),c.sort((d,h)=>this.Pu.key(d.time)-this.Pu.key(h.time)),l=this.cg(c)}return this.dg(e,l,function(c,d,h){const u=Vn(c,h),m=Vn(d,h);if(u!==void 0&&m!==void 0)return{fg:!1,Va:u.eg>=m.eg&&u.sg>=m.sg}}(this.hg.get(e),a,this.Pu))}if(e){return this.og(e,[])}pg(e,t,i){if(i&&e.Fa())throw new Error("Historical updates are not supported when conflation is enabled. Conflation requires data to be processed in order.");const n=t;(function(p){p.Qr===void 0&&(p.Qr=p.time)})(n),this.Pu.preprocessData(t);const a=this.Pu.createConverterToInternalObj([t])(t.time),o=this.ag.get(e);if(!i&&o!==void 0&&this.Pu.key(a)this.Pu.key(p.time)this.Pu.key(n.wt)?yt(t)&&i.push(t):yt(t)?i[i.length-1]=t:i.splice(-1,1),this.ag.set(e,t.wt)}vg(e,t,i){const n=this.hg.get(e);if(n===void 0)return;const a=mt(n,i,(o,l)=>o.$n{t.length!==0&&(e=Math.max(e,t[t.length-1].$n))}),e}dg(e,t,i){const n=this.Mg();if(t!==-1)this.hg.forEach((a,o)=>{n.Y_.set(o,{ue:a,bg:o===e?i:void 0})}),this.hg.has(e)||n.Y_.set(e,{ue:[],bg:i}),n.Et.Sg=this.lg,n.Et.xg=t;else{const a=this.hg.get(e);n.Y_.set(e,{ue:a||[],bg:i})}return n}Mg(){return{Y_:new Map,Et:{Dc:this.gg()}}}}function Rs(s,e){s.$n=e,s.ng.forEach(t=>{t.$n=e})}function Hm(s,e){return s._t=e-i&&s<=t+i}function Gt(s,e,t,i,n,a){const o=n-t,l=a-i;if(o===0&&l===0)return Math.hypot(s-t,e-i);const c=((s-t)*o+(e-i)*l)/(o*o+l*l),d=Math.max(0,Math.min(1,c)),h=t+o*d,u=i+l*d;return Math.hypot(s-h,e-u)}const Wi=[0,0];function Km(s,e,t){return e===void 0||e.wt!==s.wt-1?s._t-t/2:(e._t+s._t)/2}function Gm(s,e,t){return e===void 0||e.wt!==s.wt+1?s._t+t/2:(s._t+e._t)/2}function kr(s,e,t,i,n,a,o){if(e===null||e.from>=e.to||s.length===0)return null;const l=n/2+a,c=nr(s,t-l,e.from,e.to),d=ar(s,t+l,c,e.to);if(c>=d)return null;let h=Number.POSITIVE_INFINITY;for(let u=c;ue.from?s[u-1]:void 0,b=ug)continue;o(m,Wi);const p=Wi[0],v=Wi[1],S=Math.min(p,v),j=Math.max(p,v),k=S-a,C=j+a;if(i>=S&&i<=j)h=Math.min(h,0);else if(i>=k&&i<=C){const E=Math.min(Math.abs(i-S),Math.abs(j-i));h=Math.min(h,E)}}return Number.isFinite(h)?Ds(h,0,"series-range"):null}function Qm(s,e){return s.wt0&&a=i&&(l=a-1),o>0&&o({...e,...this.ae.Sa().Sh(e.wt)}))}Ag(){this.Tg=null}Ig(){const e=this.le.Et(),t=e.N().enableConflation?e.sd():0;t!==this.Rg&&(this.yg=!0,this.Rg=t),this.yg&&(this.Lg(),this.yg=!1),this.Pg&&(this.Eg(),this.Pg=!1),this.Cg&&(this.zg(),this.Cg=!1)}zg(){const e=this.ae.Ft(),t=this.le.Et();if(this.Ag(),t.Zi()||e.Zi())return;const i=t.Ee();if(i===null||this.ae.Un().Th()===0)return;const n=this.ae.Lt();n!==null&&(this.Tg=Jm(this.kg,i,this.Dg),this.Og(e,t,n.Wt),this.Ng())}}class Xm{constructor(e,t){this.Fg=e,this.Ki=t}st(e,t,i){this.Fg.draw(e,this.Ki,t,i)}}function Zm(s){switch(s){case"point":return 2;case"range":return 0;default:return 1}}class ep extends Mr{constructor(e,t,i){super(e,t,!1),this.Yh=i,this.Fg=this.Yh.renderer(),this.Vg=new Xm(this.Fg,n=>this.Wg(n))}get ga(){return this.Yh.conflationReducer}Ha(e){return this.Yh.priceValueBuilder(e)}dl(e){return this.Yh.isWhitespace(e)}Bg(e,t){const i=this.Fg.hitTest?.(e,t,o=>this.Wg(o));if(i!=null)return{ne:(n=i).distance,se:Zm(n.type),ee:"custom",gu:n.cursorStyle,te:n.objectId,ie:n.hitTestData};var n;const a=kr(this.kg,this.Tg,e,t,this.le.Et().ml(),this.ae.N().hitTestTolerance,(o,l)=>{const c=o.Hg;let d=NaN,h=NaN;if(c!==void 0&&!this.Yh.isWhitespace(c))for(const u of this.Yh.priceValueBuilder(c)){const m=this.Wg(u);m!==null&&(d=Number.isNaN(d)?m:Math.min(d,m),h=Number.isNaN(h)?m:Math.max(h,m))}l[0]=d,l[1]=h});return a===null?null:{...a,ee:"custom"}}Lg(){const e=this.ae.Sa();this.kg=this.ae.Ua().Bh().map(t=>({wt:t.$n,_t:NaN,...e.Sh(t.$n),Hg:t.ue}))}Og(e,t){t.Ic(this.kg,ns(this.Tg))}Ng(){this.Yh.update({bars:this.kg.map(tp),barSpacing:this.le.Et().ml(),visibleRange:this.Tg,conflationFactor:this.le.Et().sd()},this.ae.N())}Wg(e){const t=this.ae.Lt();return t===null?null:this.ae.Ft().Nt(e,t.Wt)}}function tp(s){return{x:s._t,time:s.wt,originalData:s.Hg,barColor:s.sh}}const sp={color:"#2196f3"},ip=(s,e,t)=>{const i=Ye(t);return new ep(s,e,i)};function Cr(s){const e={value:s.Wt[3],time:s.Qr};return s.ig!==void 0&&(e.customValues=s.ig),e}function Qn(s){const e=Cr(s);return s.R!==void 0&&(e.color=s.R),e}function rp(s){const e=Cr(s);return s.vt!==void 0&&(e.lineColor=s.vt),s.ah!==void 0&&(e.topColor=s.ah),s.oh!==void 0&&(e.bottomColor=s.oh),e}function np(s){const e=Cr(s);return s._h!==void 0&&(e.topLineColor=s._h),s.uh!==void 0&&(e.bottomLineColor=s.uh),s.dh!==void 0&&(e.topFillColor1=s.dh),s.fh!==void 0&&(e.topFillColor2=s.fh),s.ph!==void 0&&(e.bottomFillColor1=s.ph),s.mh!==void 0&&(e.bottomFillColor2=s.mh),e}function bo(s){const e={open:s.Wt[0],high:s.Wt[1],low:s.Wt[2],close:s.Wt[3],time:s.Qr};return s.ig!==void 0&&(e.customValues=s.ig),e}function ap(s){const e=bo(s);return s.R!==void 0&&(e.color=s.R),e}function op(s){const e=bo(s),{R:t,Ht:i,hh:n}=s;return t!==void 0&&(e.color=t),i!==void 0&&(e.borderColor=i),n!==void 0&&(e.wickColor=n),e}function Bs(s){return{Area:rp,Line:Qn,Baseline:np,Histogram:Qn,Bar:ap,Candlestick:op,Custom:lp}[s]}function lp(s){const e=s.Qr;return{...s.ue,time:e}}const cp={vertLine:{color:"#9598A1",width:1,style:3,visible:!0,labelVisible:!0,labelBackgroundColor:"#131722"},horzLine:{color:"#9598A1",width:1,style:3,visible:!0,labelVisible:!0,labelBackgroundColor:"#131722"},mode:1,doNotSnapToHiddenSeriesIndices:!1},dp={vertLines:{color:"#D6DCDE",style:0,visible:!0},horzLines:{color:"#D6DCDE",style:0,visible:!0}},hp={background:{type:"solid",color:"#FFFFFF"},textColor:"#191919",fontSize:12,fontFamily:Za,panes:{enableResize:!0,separatorColor:"#E0E3EB",separatorHoverColor:"rgba(178, 181, 189, 0.2)"},attributionLogo:!0,colorSpace:"srgb",colorParsers:[]},Hi={autoScale:!0,mode:0,invertScale:!1,alignLabels:!0,borderVisible:!0,borderColor:"#2B2B43",entireTextOnly:!1,visible:!1,ticksVisible:!1,scaleMargins:{bottom:.1,top:.2},minimumWidth:0,ensureEdgeTickMarksVisible:!1,tickMarkDensity:2.5},up={rightOffset:0,barSpacing:6,minBarSpacing:.5,maxBarSpacing:0,fixLeftEdge:!1,fixRightEdge:!1,lockVisibleTimeRangeOnResize:!1,rightBarStaysOnScroll:!1,borderVisible:!0,borderColor:"#2B2B43",visible:!0,timeVisible:!1,secondsVisible:!0,shiftVisibleRangeOnNewBar:!0,allowShiftVisibleRangeOnWhitespaceReplacement:!1,ticksVisible:!1,uniformDistribution:!1,minimumHeight:0,allowBoldLabels:!0,ignoreWhitespaceIndices:!1,enableConflation:!1,conflationThresholdFactor:1,precomputeConflationOnInit:!1,precomputeConflationPriority:"background"};function Yn(){return{addDefaultPane:!0,hoveredSeriesOnTop:!0,width:0,height:0,autoSize:!1,layout:hp,crosshair:cp,grid:dp,overlayPriceScales:{...Hi},leftPriceScale:{...Hi,visible:!1},rightPriceScale:{...Hi,visible:!0},defaultVisiblePriceScaleId:"right",timeScale:up,localization:{locale:Ot?navigator.language:"",dateFormat:"dd MMM 'yy"},handleScroll:{mouseWheel:!0,pressedMouseMove:!0,horzTouchDrag:!0,vertTouchDrag:!0},handleScale:{axisPressedMouseMove:{time:!0,price:!0},axisDoubleClickReset:{time:!0,price:!0},mouseWheel:!0,pinch:!0},kineticScroll:{mouse:!1,touch:!0},trackingMode:{exitMode:1}}}class go{constructor(e,t,i){this.hv=e,this.Ug=t,this.$g=i??0}applyOptions(e){this.hv.Qt().Dd(this.Ug,e,this.$g)}options(){return this.Ki().N()}width(){return ui(this.Ug)?this.hv.DM(this.Ug):0}setVisibleRange(e){this.setAutoScale(!1),this.Ki().Go(new ye(e.from,e.to))}getVisibleRange(){let e,t,i=this.Ki().ar();if(i===null)return null;if(this.Ki().ho()){const n=this.Ki().S_(),a=mo(n);i=jt(i,this.Ki().lo()),e=Number((Math.round(i.Je()/n)*n).toFixed(a)),t=Number((Math.round(i.Qe()/n)*n).toFixed(a))}else e=i.Je(),t=i.Qe();return{from:e,to:t}}setAutoScale(e){this.applyOptions({autoScale:e})}Ki(){return P(this.hv.Qt().Id(this.Ug,this.$g)).Ft}}class mp{constructor(e,t,i,n){this.hv=e,this.yt=i,this.jg=t,this.qg=n}getHeight(){return this.yt.$t()}setHeight(e){const t=this.hv.Qt(),i=t._f(this.yt);t.Ld(i,e)}getStretchFactor(){return this.yt.F_()}setStretchFactor(e){this.yt.W_(e),this.hv.Qt().ka()}paneIndex(){return this.hv.Qt()._f(this.yt)}moveTo(e){const t=this.paneIndex();t!==e&&(pe(e>=0&&ethis.jg(e))??[]}getHTMLElement(){const e=this.hv.lv();return e&&e.length!==0&&e[this.paneIndex()]?e[this.paneIndex()].fv():null}attachPrimitive(e){this.yt.ol(e),e.attached&&e.attached({chart:this.qg,requestUpdate:()=>this.yt.Qt().ka()})}detachPrimitive(e){this.yt._l(e)}priceScale(e){if(this.yt.O_(e)===null)throw new Error(`Cannot find price scale with id: ${e}`);return new go(this.hv,e,this.paneIndex())}setPreserveEmptyPane(e){this.yt.j_(e)}preserveEmptyPane(){return this.yt.q_()}addCustomSeries(e,t={},i=0){return this.qg.addCustomSeries(e,t,i)}addSeries(e,t={}){return this.qg.addSeries(e,t,this.paneIndex())}}const pp={color:"#FF0000",price:0,lineStyle:2,lineWidth:1,lineVisible:!0,axisLabelVisible:!0,title:"",axisLabelColor:"",axisLabelTextColor:""};class Jn{constructor(e){this._r=e}applyOptions(e){this._r.vr(e)}options(){return this._r.N()}Yg(){return this._r}}class fp{constructor(e,t,i,n,a,o){this.Kg=new ce,this.ae=e,this.Gg=t,this.Zg=i,this.Pu=a,this.qg=n,this.Xg=o}m(){this.Kg.m()}priceFormatter(){return this.ae.sl()}priceToCoordinate(e){const t=this.ae.Lt();return t===null?null:this.ae.Ft().Nt(e,t.Wt)}coordinateToPrice(e){const t=this.ae.Lt();return t===null?null:this.ae.Ft().Tn(e,t.Wt)}barsInLogicalRange(e){if(e===null)return null;const t=new Mt(new Xt(e.from,e.to)).Uu(),i=this.ae.Un();if(i.Zi())return null;const n=i.Hn(t.Na(),1),a=i.Hn(t.bi(),-1),o=P(i.Rh()),l=P(i.Qn());if(n!==null&&a!==null&&n.$n>a.$n)return{barsBefore:e.from-o,barsAfter:l-e.to};const c={barsBefore:n===null||n.$n===o?e.from-o:n.$n-o,barsAfter:a===null||a.$n===l?l-e.to:l-a.$n};return n!==null&&a!==null&&(c.from=n.Qr,c.to=a.Qr),c}setData(e){this.Pu,this.ae.bh(),this.Gg.Jg(this.ae,e),this.Qg("full")}update(e,t=!1){this.ae.bh(),this.Gg.tb(this.ae,e,t),this.Qg("update")}pop(e=1){const t=this.Gg.ib(this.ae,e);t.length!==0&&this.Qg("update");const i=Bs(this.seriesType());return t.map(n=>i(n))}dataByIndex(e,t){const i=this.ae.Un().Hn(e,t);return i===null?null:Bs(this.seriesType())(i)}data(){const e=Bs(this.seriesType());return this.ae.Un().Bh().map(t=>e(t))}subscribeDataChanged(e){this.Kg.i(e)}unsubscribeDataChanged(e){this.Kg._(e)}applyOptions(e){this.ae.vr(e)}options(){return $e(this.ae.N())}priceScale(){return this.Zg.priceScale(this.ae.Ft().pl(),this.getPane().paneIndex())}createPriceLine(e){const t=Me($e(pp),e),i=this.ae.Ea(t);return new Jn(i)}removePriceLine(e){this.ae.Aa(e.Yg())}priceLines(){return this.ae.La().map(e=>new Jn(e))}seriesType(){return this.ae.bh()}lastValueData(e){const t=this.ae.Ae(e);return t.Le?{noData:!0}:{noData:!1,price:t.Mt,color:t.R}}attachPrimitive(e){this.ae.ol(e),e.attached&&e.attached({chart:this.qg,series:this,requestUpdate:()=>this.ae.Qt().ka(),horzScaleBehavior:this.Pu})}detachPrimitive(e){this.ae._l(e),e.detached&&e.detached(),this.ae.Qt().ka()}getPane(){const e=this.ae,t=P(this.ae.Qt().Ks(e));return this.Xg(t)}moveToPane(e){this.ae.Qt().rf(this.ae,e)}seriesOrder(){const e=this.ae.Qt().Ks(this.ae);return e===null?-1:e.Y_().indexOf(this.ae)}setSeriesOrder(e){const t=this.ae.Qt().Ks(this.ae);t!==null&&t.vu(this.ae,e)}Qg(e){this.Kg.v()&&this.Kg.p(e)}}class xp{constructor(e,t,i){this.nb=new ce,this.Qu=new ce,this.Nw=new ce,this.sn=e,this.ia=e.Et(),this.vM=t,this.ia.Zc().i(this.sb.bind(this)),this.ia.Xc().i(this.eb.bind(this)),this.vM.qw().i(this.rb.bind(this)),this.Pu=i}m(){this.ia.Zc().u(this),this.ia.Xc().u(this),this.vM.qw().u(this),this.nb.m(),this.Qu.m(),this.Nw.m()}scrollPosition(){return this.ia.Oc()}scrollToPosition(e,t){t?this.ia.Yc(e,1e3):this.sn.gs(e)}scrollToRealTime(){this.ia.qc()}getVisibleRange(){const e=this.ia.xc();return e===null?null:{from:e.from.originalTime,to:e.to.originalTime}}setVisibleRange(e){const t={from:this.Pu.convertHorzItemToInternal(e.from),to:this.Pu.convertHorzItemToInternal(e.to)},i=this.ia.kc(t);this.sn.sf(i)}getVisibleLogicalRange(){const e=this.ia.Sc();return e===null?null:{from:e.Na(),to:e.bi()}}setVisibleLogicalRange(e){pe(e.from<=e.to,"The from index cannot be after the to index."),this.sn.sf(e)}resetTimeScale(){this.sn.ws()}fitContent(){this.sn.td()}logicalToCoordinate(e){const t=this.sn.Et();return t.Zi()?null:t.jt(e)}coordinateToLogical(e){return this.ia.Zi()?null:this.ia.Vc(e)}timeToIndex(e,t){const i=this.Pu.convertHorzItemToInternal(e);return this.ia.Mc(i,t)}timeToCoordinate(e){const t=this.timeToIndex(e,!1);return t===null?null:this.ia.jt(t)}coordinateToTime(e){const t=this.sn.Et(),i=t.Vc(e),n=t.en(i);return n===null?null:n.originalTime}width(){return this.vM.pv().width}height(){return this.vM.pv().height}subscribeVisibleTimeRangeChange(e){this.nb.i(e)}unsubscribeVisibleTimeRangeChange(e){this.nb._(e)}subscribeVisibleLogicalRangeChange(e){this.Qu.i(e)}unsubscribeVisibleLogicalRangeChange(e){this.Qu._(e)}subscribeSizeChange(e){this.Nw.i(e)}unsubscribeSizeChange(e){this.Nw._(e)}applyOptions(e){this.ia.vr(e)}options(){return{...$e(this.ia.N()),barSpacing:this.ia.ml()}}sb(){this.nb.v()&&this.nb.p(this.getVisibleRange())}eb(){this.Qu.v()&&this.Qu.p(this.getVisibleLogicalRange())}rb(e){this.Nw.p(e.width,e.height)}}function Xn(s){return function(e){if(Ns(e.handleScale)){const i=e.handleScale;e.handleScale={axisDoubleClickReset:{time:i,price:i},axisPressedMouseMove:{time:i,price:i},mouseWheel:i,pinch:i}}else if(e.handleScale!==void 0){const{axisPressedMouseMove:i,axisDoubleClickReset:n}=e.handleScale;Ns(i)&&(e.handleScale.axisPressedMouseMove={time:i,price:i}),Ns(n)&&(e.handleScale.axisDoubleClickReset={time:n,price:n})}const t=e.handleScroll;Ns(t)&&(e.handleScroll={horzTouchDrag:t,vertTouchDrag:t,mouseWheel:t,pressedMouseMove:t})}(s),s}class bp{constructor(e,t,i){this.hb=new Map,this.ab=new Map,this.lb=new ce,this.ob=new ce,this._b=new ce,this.dd=new WeakMap,this.ub=new Wm(t);const n=i===void 0?$e(Yn()):Me($e(Yn()),Xn(i));this.cb=t,this.hv=new zm(e,n,t),this.hv.mw().i(o=>{this.lb.v()&&this.lb.p(this.fb(o()))},this),this.hv.ww().i(o=>{this.ob.v()&&this.ob.p(this.fb(o()))},this),this.hv.Bd().i(o=>{this._b.v()&&this._b.p(this.fb(o()))},this);const a=this.hv.Qt();this.pb=new xp(a,this.hv.bM(),this.cb)}remove(){this.hv.mw().u(this),this.hv.ww().u(this),this.hv.Bd().u(this),this.pb.m(),this.hv.m(),this.hb.clear(),this.ab.clear(),this.lb.m(),this.ob.m(),this._b.m(),this.ub.m()}resize(e,t,i){this.autoSizeActive()||this.hv.wM(e,t,i)}addCustomSeries(e,t={},i=0){const n=(a=>({type:"Custom",isBuiltIn:!1,defaultOptions:{...sp,...a.defaultOptions()},mb:ip,wb:a}))(Ye(e));return this.Mb(n,t,i)}addSeries(e,t={},i=0){return this.Mb(e,t,i)}removeSeries(e){const t=_e(this.hb.get(e)),i=this.ub.if(t);this.hv.Qt().if(t),this.gb(i),this.hb.delete(e),this.ab.delete(t)}Jg(e,t){this.gb(this.ub.og(e,t))}tb(e,t,i){this.gb(this.ub.pg(e,t,i))}ib(e,t){const[i,n]=this.ub.wg(e,t);return i.length!==0&&this.gb(n),i}subscribeClick(e){this.lb.i(e)}unsubscribeClick(e){this.lb._(e)}subscribeCrosshairMove(e){this._b.i(e)}unsubscribeCrosshairMove(e){this._b._(e)}subscribeDblClick(e){this.ob.i(e)}unsubscribeDblClick(e){this.ob._(e)}priceScale(e,t=0){return new go(this.hv,e,t)}timeScale(){return this.pb}applyOptions(e){this.hv.vr(Xn(e))}options(){return this.hv.N()}takeScreenshot(e=!1,t=!1){let i,n;try{t||(i=this.hv.Qt().N().crosshair.mode,this.hv.vr({crosshair:{mode:2}})),n=this.hv.TM(e)}finally{t||i===void 0||this.hv.Qt().vr({crosshair:{mode:i}})}return n}addPane(e=!1){const t=this.hv.Qt().uf();return t.j_(e),this.bb(t)}removePane(e){this.hv.Qt().Ad(e)}swapPanes(e,t){this.hv.Qt().zd(e,t)}autoSizeActive(){return this.hv.CM()}chartElement(){return this.hv.Mv()}panes(){return this.hv.Qt().Gn().map(e=>this.bb(e))}paneSize(e=0){const t=this.hv.AM(e);return{height:t.height,width:t.width}}setCrosshairPosition(e,t,i){const n=this.hb.get(i);if(n===void 0)return;const a=this.hv.Qt().Ks(n);a!==null&&this.hv.Qt().Gd(e,t,a)}clearCrosshairPosition(){this.hv.Qt().Zd(!0)}horzBehaviour(){return this.cb}Mb(e,t={},i=0){pe(e.mb!==void 0),function(c){if(c===void 0||c.type==="custom")return;const d=c;d.minMove!==void 0&&d.precision===void 0&&(d.precision=mo(d.minMove))}(t.priceFormat),e.type==="Candlestick"&&function(c){c.borderColor!==void 0&&(c.borderUpColor=c.borderColor,c.borderDownColor=c.borderColor),c.wickColor!==void 0&&(c.wickUpColor=c.wickColor,c.wickDownColor=c.wickColor)}(t);const n=Me($e(Ja),$e(e.defaultOptions),t),a=e.mb,o=new pi(this.hv.Qt(),e.type,n,a,e.wb);this.hv.Qt().Qd(o,i);const l=new fp(o,this,this,this,this.cb,c=>this.bb(c));return this.hb.set(l,o),this.ab.set(o,l),l}gb(e){const t=this.hv.Qt();for(const i of e.Y_.keys())i.Ia();t.Xd(e.Et.Dc,e.Et.Sg,e.Et.xg),e.Y_.forEach((i,n)=>n.ht(i.ue,i.bg)),t.Et().dc(),t.Lc()}Sb(e){return _e(this.ab.get(e))}xb(e){return e!==void 0&&this.ab.has(e)?this.Sb(e):void 0}fb(e){const t=new Map;e.QM.forEach((a,o)=>{const l=o.bh(),c=Bs(l)(a);if(l!=="Custom")pe($m(c));else{const d=o.cl();pe(!d||d(c)===!1)}t.set(this.Sb(o),c)});const i=this.xb(e.jM),n=e.YM===void 0?void 0:{type:e.YM.ds,sourceKind:e.YM.KM,objectKind:e.YM.GM,series:this.xb(e.YM.Y_),objectId:e.YM.ZM,paneIndex:e.YM.XM};return{time:e.Qr,logical:e.$n,point:e.JM,paneIndex:e.XM,hoveredInfo:n,hoveredSeries:i,hoveredObjectId:e.qM,seriesData:t,sourceEvent:e.tg}}bb(e){let t=this.dd.get(e);return t||(t=new mp(this.hv,i=>this.Sb(i),e,this),this.dd.set(e,t)),t}}function gp(s){if(fs(s)){const e=document.getElementById(s);return pe(e!==null,`Cannot find element in DOM with id=${s}`),e}return s}function vp(s,e,t){const i=gp(s),n=new bp(i,e,t);return e.setOptions(n.options()),n}function xi(s,e){return vp(s,new On,On.Tf(e))}function Vt(s,e,t,i){return Math.hypot(t-s,i-e)}function vo(s,e,t,i,n,a,o,l=0){if(e.length===0||i.from>=e.length||i.to<=0)return;const{context:c,horizontalPixelRatio:d,verticalPixelRatio:h}=s,u=e[i.from];let m=a(s,u),x=u;if(i.to-i.from<2){const b=n/2;c.beginPath();const f={_t:u._t-b,ut:u.ut},g={_t:u._t+b,ut:u.ut};c.moveTo(f._t*d,f.ut*h),c.lineTo(g._t*d,g.ut*h),o(s,m,f,g)}else{const b=l>0;let f=0;const g=(v,S)=>{if(o(s,m,x,S),c.beginPath(),m=v,x=S,b){const j=f%l;c.lineDashOffset=j,f=j}};let p=x;c.beginPath(),c.moveTo(u._t*d,u.ut*h);for(let v=i.from+1;vb+f,0)}(h);a!==void 0&&vo(e,t,a,i,n,u,yp,m),c&&function(x,b,f,g,p){if(g.to-g.from<=0)return;const{horizontalPixelRatio:v,verticalPixelRatio:S,context:j}=x;let k=null;const C=Math.max(1,Math.floor(v))%2/2,E=f*S+C;for(let T=g.to-1;T>=g.from;--T){const D=b[T];if(D){const O=p(x,D);O!==k&&(k!==null&&j.fill(),j.beginPath(),j.fillStyle=O,k=O);const M=Math.round(D._t*v)+C,R=D.ut*S;j.moveTo(M,R),j.arc(M,R,E,0,2*Math.PI)}}j.fill()}(e,t,c,i,u)}}class yo extends wp{kb(e,t){return t.vt}}function ta(s,e,t,i,n){const a=1-n;return a*a*a*s+3*a*a*n*e+3*a*n*n*t+n*n*n*i}function Np(s,e,t,i,n){if(t===2){const[a,o]=Er(i,n-1,n);return[Math.min(s._t,e._t,a._t,o._t),Math.max(s._t,e._t,a._t,o._t)]}return[Math.min(s._t,e._t),Math.max(s._t,e._t)]}function jp(s,e,t,i,n,a,o,l){switch(n){case 1:{const c=Gt(s,e,t._t,t.ut,i._t,t.ut),d=Gt(s,e,i._t,t.ut,i._t,i.ut),h=Math.min(c,d);return h<=l?h:null}case 2:{const[c,d]=Er(a,o-1,o),h=function(u,m,x){let b=Number.POSITIVE_INFINITY,f=x[0];for(let g=1;g<=12;g++){const p=g/12,v={_t:ta(x[0]._t,x[1]._t,x[2]._t,x[3]._t,p),ut:ta(x[0].ut,x[1].ut,x[2].ut,x[3].ut,p)};b=Math.min(b,Gt(u,m,f._t,f.ut,v._t,v.ut)),f=v}return b}(s,e,[t,c,d,i]);return h<=l?h:null}default:{const c=Gt(s,e,t._t,t.ut,i._t,i.ut);return c<=l?c:null}}}class wo extends Mr{constructor(e,t){super(e,t,!0)}Og(e,t,i){t.Ic(this.kg,ns(this.Tg)),e.Jo(this.kg,i,ns(this.Tg))}Tb(e,t){return{wt:e,Mt:t,_t:NaN,ut:NaN}}Lg(){const e=this.ae.Sa();this.kg=this.ae.Ua().Bh().map(t=>{let i;if((t.Gr??1)>1){const n=t.Wt[1],a=t.Wt[2],o=t.Wt[3];i=Math.abs(n-o)>Math.abs(a-o)?n:a}else i=t.Wt[3];return this.Rb(t.$n,i,e)})}}class No extends wo{Bg(e,t){const i=this.ae.N();return function(n,a,o,l,c,d,h,u=0,m=0){if(a===null||a.from>=a.to||n.length===0)return null;const x=Math.max(d/2,h??0)+m;let b=Number.POSITIVE_INFINITY;if(h!==void 0){const j=h+m,k=nr(n,o-j,a.from,a.to),C=ar(n,o+j,k,a.to);for(let E=k;Enew _p(s,e)};function kp(s,e,t,i,n){const{context:a,horizontalPixelRatio:o,verticalPixelRatio:l}=e;a.lineTo(n._t*o,s*l),a.lineTo(i._t*o,s*l),a.closePath(),a.fillStyle=t,a.fill()}class Mp extends Ue{constructor(){super(...arguments),this.rt=null}ht(e){this.rt=e}et(e){if(this.rt===null)return;const{ot:t,lt:i,Cb:n,ct:a,Gt:o,yb:l}=this.rt,c=this.rt.Lb??(this.rt.zb?0:e.mediaSize.height);if(i===null)return;const d=e.context;d.lineCap="butt",d.lineJoin="round",d.lineWidth=a,et(d,o),d.lineWidth=1,vo(e,t,l,i,n,this.Ob.bind(this),kp.bind(null,c))}}class Cp{Nb(e,t){const i=this.Fb,{Wb:n,Hb:a,Ub:o,$b:l,Lb:c,jb:d,qb:h}=t;if(this.Yb===void 0||i===void 0||i.Wb!==n||i.Hb!==a||i.Ub!==o||i.$b!==l||i.Lb!==c||i.jb!==d||i.qb!==h){const{verticalPixelRatio:u}=e,m=c||d>0?u:1,x=d*m,b=h===e.bitmapSize.height?h:h*m,f=(c??0)*m,g=e.context.createLinearGradient(0,x,0,b);if(g.addColorStop(0,n),c!=null){const p=kt((f-x)/(b-x),0,1);g.addColorStop(p,a),g.addColorStop(p,o)}g.addColorStop(1,l),this.Yb=g,this.Fb=t}return this.Yb}}class Ep{constructor(e,t,i,n){this.Zb=e,this.Xb=t,this.Jb=i,this.Qb=n}st(e,t,i){this.Zb.st(e,t,i),!this.Jb()||t&&this.Qb()||this.Xb.st(e,t,i)}}class Tp{constructor(e,t){this.Xb=e,this.tS=t}Tt(){return this.tS()?this.Xb:null}}class Rp extends Mp{constructor(){super(...arguments),this.Kb=new Cp}Ob(e,t){return this.Kb.Nb(e,{Wb:t.ah,Hb:"",Ub:"",$b:t.oh,jb:this.rt?.jb??0,qb:e.bitmapSize.height})}}class Pp extends No{constructor(e,t){super(e,t),this.lS=new Rp,this.Xb=new yo,this.sS=new Tp(this.Xb,()=>this.Jb()),this.eS=[this],this.rS=[this.sS],this.hS={Za:this.eS,qa:this.rS},this.Vg=new Ep(this.lS,this.Xb,()=>this.Jb(),()=>this.le.N().hoveredSeriesOnTop)}Ga(){return this.hS}Rb(e,t,i){return{...this.Tb(e,t),...i.Sh(e)}}Ng(){const e=this.ae.N();if(this.Tg===null||this.kg.length===0)return;let t;if(e.relativeGradient){t=this.kg[this.Tg.from].ut;for(let i=this.Tg.from;inew Pp(s,e)};class Ap extends Mr{constructor(e,t){super(e,t,!1)}Bg(e,t){return kr(this.kg,this.Tg,e,t,this.le.Et().ml(),this.ae.N().hitTestTolerance,(i,n)=>{n[0]=i.n_,n[1]=i.s_})}Og(e,t,i){t.Ic(this.kg,ns(this.Tg)),e.t_(this.kg,i,ns(this.Tg))}fS(e,t,i){return{wt:e,jr:t.Wt[0],qr:t.Wt[1],Yr:t.Wt[2],Kr:t.Wt[3],_t:NaN,i_:NaN,n_:NaN,s_:NaN,e_:NaN}}Lg(){const e=this.ae.Sa();this.kg=this.ae.Ua().Bh().map(t=>this.Rb(t.$n,t,e))}}class Op extends Ue{constructor(){super(...arguments),this.qt=null,this.oS=0}ht(e){this.qt=e}et(e){if(this.qt===null||this.qt.Un.length===0||this.qt.lt===null)return;const{horizontalPixelRatio:t}=e;this.oS=function(a,o){if(a>=2.5&&a<=4)return Math.floor(3*o);const l=1-.2*Math.atan(Math.max(4,a)-4)/(.5*Math.PI),c=Math.floor(a*l*o),d=Math.floor(a*o),h=Math.min(c,d);return Math.max(Math.floor(o),h)}(this.qt.ml,t),this.oS>=2&&Math.floor(t)%2!=this.oS%2&&this.oS--;const i=this.qt.Un;this.qt.pS&&this.vS(e,i,this.qt.lt),this.qt.gi&&this.Vm(e,i,this.qt.lt);const n=this.mS(t);(!this.qt.gi||this.oS>2*n)&&this.wS(e,i,this.qt.lt)}vS(e,t,i){if(this.qt===null)return;const{context:n,horizontalPixelRatio:a,verticalPixelRatio:o}=e;let l="",c=Math.min(Math.floor(a),Math.floor(this.qt.ml*a));c=Math.max(Math.floor(a),Math.min(c,this.oS));const d=Math.floor(.5*c);let h=null;for(let u=i.from;u2*c)Nu(n,m,b,x-m+1,f-b+1,c);else{const g=x-m+1;n.fillRect(m,b,g,f-b+1)}d=x}}wS(e,t,i){if(this.qt===null)return;const{context:n,horizontalPixelRatio:a,verticalPixelRatio:o}=e;let l="";const c=this.mS(a);for(let d=i.from;dm||n.fillRect(x,u,b-x+1,m-u+1)}}}class zp extends Ap{constructor(){super(...arguments),this.Vg=new Op}Rb(e,t,i){return{...this.fS(e,t,i),...i.Sh(e)}}Ng(){const e=this.ae.N();this.Vg.ht({Un:this.kg,ml:this.le.Et().ml(),pS:e.wickVisible,gi:e.borderVisible,lt:this.Tg})}}const Ip={type:"Candlestick",isBuiltIn:!0,defaultOptions:{upColor:"#26a69a",downColor:"#ef5350",wickVisible:!0,borderVisible:!0,borderColor:"#378658",borderUpColor:"#26a69a",borderDownColor:"#ef5350",wickColor:"#737375",wickUpColor:"#26a69a",wickDownColor:"#ef5350"},mb:(s,e)=>new zp(s,e)};class $p extends Ue{constructor(){super(...arguments),this.qt=null,this.MS=[]}ht(e){this.qt=e,this.MS=[]}et({context:e,horizontalPixelRatio:t,verticalPixelRatio:i}){if(this.qt===null||this.qt.ot.length===0||this.qt.lt===null)return;this.MS.length||this.gS(t);const n=Math.max(1,Math.floor(i)),a=Math.round(this.qt.bS*i)-Math.floor(n/2),o=a+n;for(let l=this.qt.lt.from;ll.ce?l.bi=o.Na-t-1:o.Na=l.bi+t+1)}let n=Math.ceil(this.qt.ml*e);for(let a=this.qt.lt.from;a0&&n<4)for(let a=this.qt.lt.from;an&&(o.SS>o.ce?o.bi-=1:o.Na+=1)}}}class Dp extends wo{constructor(){super(...arguments),this.Vg=new $p}Bg(e,t){const i=this.ae.Ft().Nt(this.ae.N().base,P(this.ae.Lt()).Wt);return i===null?null:kr(this.kg,this.Tg,e,t,this.le.Et().ml(),this.ae.N().hitTestTolerance,(n,a)=>{a[0]=n.ut,a[1]=i})}Rb(e,t,i){return{...this.Tb(e,t),...i.Sh(e)}}Ng(){const e={ot:this.kg,ml:this.le.Et().ml(),lt:this.Tg,bS:this.ae.Ft().Nt(this.ae.N().base,P(this.ae.Lt()).Wt)};this.Vg.ht(e)}}const Tr={type:"Histogram",isBuiltIn:!0,defaultOptions:{color:"#26a69a",base:0},mb:(s,e)=>new Dp(s,e)};({...Ja});function Bp(s){return!s||isNaN(s)||s<=0?{type:"price",precision:2,minMove:.01}:s<1e-5?{type:"price",precision:8,minMove:1e-8}:s<.001?{type:"price",precision:6,minMove:1e-6}:s<.1?{type:"price",precision:5,minMove:1e-5}:s<1?{type:"price",precision:4,minMove:1e-4}:s<10?{type:"price",precision:3,minMove:.001}:{type:"price",precision:2,minMove:.01}}function Ps(s){return s==null||isNaN(s)?"-":s>=1e3?s.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):s>=1?s.toFixed(4):s>=.01?s.toFixed(6):s.toFixed(8)}function Fp({candles:s,symbol:e,overlays:t,height:i=520,isLoading:n=!1}){const a=y.useRef(null),o=y.useRef(null),l=y.useRef(null),c=y.useRef(null),d=y.useRef([]),h=y.useRef(!1),u=y.useRef(e),m=y.useRef(null),[x,b]=y.useState(null);y.useEffect(()=>{if(!a.current)return;const p=xi(a.current,{width:a.current.clientWidth,height:i,layout:{background:{type:At.Solid,color:"#090b0e"},textColor:"#94a3b8",fontSize:11,fontFamily:"JetBrains Mono, ui-monospace, SFMono-Regular, monospace"},grid:{vertLines:{color:"rgba(30, 41, 59, 0.4)",style:he.SparseDotted},horzLines:{color:"rgba(30, 41, 59, 0.4)",style:he.SparseDotted}},crosshair:{mode:Lt.Normal,vertLine:{color:"#38bdf8",width:1,style:he.Dashed,labelBackgroundColor:"#0284c7"},horzLine:{color:"#38bdf8",width:1,style:he.Dashed,labelBackgroundColor:"#0284c7"}},rightPriceScale:{borderColor:"#1e293b",autoScale:!0,scaleMargins:{top:.1,bottom:.22}},timeScale:{borderColor:"#1e293b",timeVisible:!0,secondsVisible:!1}});o.current=p;const v=p.addSeries(Ip,{upColor:"#10b981",downColor:"#ef4444",borderVisible:!1,wickUpColor:"#10b981",wickDownColor:"#ef4444",priceFormat:{type:"price",precision:2,minMove:.01}});l.current=v;const S=p.addSeries(Tr,{color:"#64748b",priceFormat:{type:"volume"},priceScaleId:"volume"});p.priceScale("volume").applyOptions({scaleMargins:{top:.8,bottom:0},visible:!1}),c.current=S,p.subscribeCrosshairMove(C=>{if(!C.time||!C.seriesData){b(null);return}const E=C.seriesData.get(v),T=C.seriesData.get(S);E&&b({time:Number(C.time),open:E.open,high:E.high,low:E.low,close:E.close,volume:T?.value})});const j=()=>{a.current&&o.current&&o.current.applyOptions({width:a.current.clientWidth})};window.addEventListener("resize",j);const k=new ResizeObserver(j);return k.observe(a.current),()=>{window.removeEventListener("resize",j),k.disconnect(),p.remove(),o.current=null,l.current=null,c.current=null,d.current=[],h.current=!1,m.current=null}},[i]),y.useEffect(()=>{if(u.current!==e){u.current=e,m.current=null,h.current=!1,b(null);try{l.current?.setData([]),c.current?.setData([])}catch{}d.current.forEach(p=>{try{l.current?.removePriceLine(p)}catch{}}),d.current=[]}},[e]),y.useEffect(()=>{if(!l.current||!c.current)return;if(!s||s.length===0){h.current=!1,m.current=null;try{l.current.setData([]),c.current.setData([])}catch{}return}const p=new Map;for(const M of s)M&&M.time&&!isNaN(M.time)&&!isNaN(M.close)&&M.close>0&&!isNaN(M.open)&&!isNaN(M.high)&&!isNaN(M.low)&&p.set(M.time,M);const v=Array.from(p.values()).sort((M,R)=>M.time-R.time);if(v.length===0)return;const S=Math.floor(v.length/2),j=v[S]?.close||v[0].close,k=v.filter(M=>{if(j>0){const R=M.close/j;return R>=.1&&R<=10}return!0});if(k.length===0)return;const C=k[0].time,E=m.current!==C,T=!h.current||E,D=k[k.length-1],O=Bp(D.close);if(l.current.applyOptions({priceFormat:O}),T){m.current=C;const M=k.map(L=>({time:L.time,open:L.open,high:L.high,low:L.low,close:L.close})),R=k.map(L=>({time:L.time,value:L.volume||0,color:L.close>=L.open?"rgba(16, 185, 129, 0.35)":"rgba(239, 68, 68, 0.35)"}));try{l.current.setData(M),c.current.setData(R),o.current?.timeScale().fitContent(),h.current=!0}catch{}}else{const M=k[k.length-1];try{l.current.update({time:M.time,open:M.open,high:M.high,low:M.low,close:M.close}),c.current.update({time:M.time,value:M.volume||0,color:M.close>=M.open?"rgba(16, 185, 129, 0.35)":"rgba(239, 68, 68, 0.35)"})}catch{const L=k.map(z=>({time:z.time,open:z.open,high:z.high,low:z.low,close:z.close})),$=k.map(z=>({time:z.time,value:z.volume||0,color:z.close>=z.open?"rgba(16, 185, 129, 0.35)":"rgba(239, 68, 68, 0.35)"}));try{l.current.setData(L),c.current.setData($),o.current?.timeScale().fitContent()}catch{}}}},[s,e,i]),y.useEffect(()=>{if(!l.current)return;d.current.forEach(E=>{try{l.current?.removePriceLine(E)}catch{}}),d.current=[];const p=l.current,v=t?.showLevels!==!1,S=t?.showMagnets!==!1,k=(s&&s.length>0?s[s.length-1]:null)?.close||0,C=E=>{if(!E||isNaN(E)||E<=0)return!1;if(k>0){const T=E/k;return T>=.2&&T<=5}return!0};if(v&&t?.entryPrice&&C(t.entryPrice)){const E=p.createPriceLine({price:t.entryPrice,color:"#38bdf8",lineWidth:2,lineStyle:he.Dashed,axisLabelVisible:!0,title:"ENTRY ZONE"});d.current.push(E)}if(v&&t?.stopLoss&&C(t.stopLoss)){const E=p.createPriceLine({price:t.stopLoss,color:"#f43f5e",lineWidth:2,lineStyle:he.Dashed,axisLabelVisible:!0,title:"STOP LOSS"});d.current.push(E)}if(v&&t?.takeProfit1&&C(t.takeProfit1)){const E=p.createPriceLine({price:t.takeProfit1,color:"#10b981",lineWidth:2,lineStyle:he.Dashed,axisLabelVisible:!0,title:"TP1 (50%)"});d.current.push(E)}if(v&&t?.takeProfit2&&C(t.takeProfit2)){const E=p.createPriceLine({price:t.takeProfit2,color:"#34d399",lineWidth:2,lineStyle:he.Dashed,axisLabelVisible:!0,title:"TP2 (RUNNER)"});d.current.push(E)}if(v&&t?.invalidation&&C(t.invalidation)){const E=p.createPriceLine({price:t.invalidation,color:"#fbbf24",lineWidth:1,lineStyle:he.Dotted,axisLabelVisible:!0,title:"INVALIDATION"});d.current.push(E)}if(S&&t?.upperMagnet&&C(t.upperMagnet)){const E=p.createPriceLine({price:t.upperMagnet,color:"#a855f7",lineWidth:1,lineStyle:he.Dotted,axisLabelVisible:!0,title:"🧲 LIQ MAGNET UPPER"});d.current.push(E)}if(S&&t?.lowerMagnet&&C(t.lowerMagnet)){const E=p.createPriceLine({price:t.lowerMagnet,color:"#a855f7",lineWidth:1,lineStyle:he.Dotted,axisLabelVisible:!0,title:"🧲 LIQ MAGNET LOWER"});d.current.push(E)}},[t,s,e,i]);const f=s&&s.length>0?s[s.length-1]:null,g=x||f;return r.jsxs("div",{className:"relative w-full rounded-2xl bg-[#090b0e] border border-border/80 overflow-hidden shadow-2xl flex flex-col",children:[r.jsxs("div",{className:"px-4 py-2.5 bg-bg-card/90 border-b border-border/60 flex flex-wrap items-center justify-between gap-3 text-xs font-mono",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"font-bold text-text-primary text-sm tracking-wide",children:e}),g&&r.jsxs("div",{className:"hidden sm:flex items-center gap-2.5 text-[11px]",children:[r.jsxs("span",{className:"text-text-muted",children:["O: ",r.jsx("span",{className:"text-text-primary",children:Ps(g.open)})]}),r.jsxs("span",{className:"text-text-muted",children:["H: ",r.jsx("span",{className:"text-text-primary",children:Ps(g.high)})]}),r.jsxs("span",{className:"text-text-muted",children:["L: ",r.jsx("span",{className:"text-text-primary",children:Ps(g.low)})]}),r.jsxs("span",{className:"text-text-muted",children:["C:"," ",r.jsx("span",{className:g.close&&g.open&&g.close>=g.open?"text-emerald-400 font-semibold":"text-rose-400 font-semibold",children:Ps(g.close)})]}),g.volume!==void 0&&r.jsxs("span",{className:"text-text-muted",children:["Vol: ",r.jsx("span",{className:"text-text-secondary",children:Math.round(g.volume).toLocaleString()})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2 text-[10px]",children:[t?.showLevels!==!1&&r.jsxs("span",{className:"flex items-center gap-1 text-sky-400 bg-sky-500/10 px-2 py-0.5 rounded border border-sky-500/20",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-sky-400"})," Levels Sinyal"]}),t?.showMagnets!==!1&&r.jsxs("span",{className:"flex items-center gap-1 text-purple-400 bg-purple-500/10 px-2 py-0.5 rounded border border-purple-500/20",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-purple-400"})," Likuidasi Magnet"]})]})]}),r.jsxs("div",{className:"relative w-full flex-1 min-h-[420px]",children:[r.jsx("div",{ref:a,className:"w-full h-full min-h-[420px]"}),n&&r.jsxs("div",{className:"absolute inset-0 bg-[#090b0e]/80 backdrop-blur-sm flex flex-col items-center justify-center gap-2.5 z-10 font-mono text-xs text-text-muted",children:[r.jsx(Yo,{className:"w-6 h-6 animate-spin text-accent-blue"}),r.jsxs("span",{children:["Memuat data candlestick ",e,"..."]})]}),!n&&(!s||s.length===0)&&r.jsxs("div",{className:"absolute inset-0 bg-[#090b0e]/90 flex flex-col items-center justify-center gap-2 z-10 font-mono text-xs text-text-muted",children:[r.jsx(or,{className:"w-6 h-6 text-amber-400"}),r.jsxs("span",{children:["Data grafik untuk ",e," sedang dimuat atau belum tersedia"]})]})]})]})}function Up(s){if(isNaN(s)||s===0)return"0";const e=s>0?"+":"",t=Math.abs(s);return t>=1e9?`${e}${(s/1e9).toFixed(2)}B`:t>=1e6?`${e}${(s/1e6).toFixed(2)}M`:t>=1e3?`${e}${s.toLocaleString("en-US",{minimumFractionDigits:1,maximumFractionDigits:2})}`:`${e}${s.toFixed(2)}`}function qp({candles:s,symbol:e,height:t=180}){const i=y.useRef(null),n=y.useRef(null),a=y.useRef(null),o=y.useRef(null),l=y.useRef(!1),c=y.useRef(null),d=y.useRef(e);y.useEffect(()=>{if(!i.current)return;const m=xi(i.current,{width:i.current.clientWidth,height:t,layout:{background:{type:At.Solid,color:"#090b0e"},textColor:"#94a3b8",fontSize:10,fontFamily:"JetBrains Mono, ui-monospace, monospace"},grid:{vertLines:{color:"rgba(30, 41, 59, 0.3)",style:he.SparseDotted},horzLines:{color:"rgba(30, 41, 59, 0.3)",style:he.SparseDotted}},crosshair:{mode:Lt.Normal},rightPriceScale:{borderColor:"#1e293b",autoScale:!0},timeScale:{borderColor:"#1e293b",timeVisible:!0,secondsVisible:!1}});n.current=m;const x=m.addSeries(Tr,{color:"#38bdf8",priceFormat:{type:"volume"},priceScaleId:"right"});o.current=x;const b=m.addSeries(Sp,{color:"#f59e0b",lineWidth:2,crosshairMarkerVisible:!0});a.current=b;const f=()=>{i.current&&n.current&&n.current.applyOptions({width:i.current.clientWidth})};window.addEventListener("resize",f);const g=new ResizeObserver(f);return g.observe(i.current),()=>{window.removeEventListener("resize",f),g.disconnect(),m.remove(),n.current=null,a.current=null,o.current=null,l.current=!1,c.current=null}},[t]),y.useEffect(()=>{if(d.current!==e){d.current=e,c.current=null,l.current=!1;try{a.current?.setData([]),o.current?.setData([])}catch{}}},[e]),y.useEffect(()=>{if(!a.current||!o.current)return;if(!s||s.length===0){l.current=!1,c.current=null;try{a.current.setData([]),o.current.setData([])}catch{}return}const m=new Map;for(const p of s)p&&p.time&&!isNaN(p.time)&&m.set(p.time,p);const x=Array.from(m.values()).sort((p,v)=>p.time-v.time);if(x.length===0)return;const b=x[0].time,f=c.current!==b;if(!l.current||f){c.current=b;const p=x.filter(S=>S.cvd!==void 0&&!isNaN(S.cvd)).map(S=>({time:S.time,value:S.cvd})),v=x.filter(S=>S.delta!==void 0&&!isNaN(S.delta)).map(S=>({time:S.time,value:S.delta,color:(S.delta||0)>=0?"rgba(16, 185, 129, 0.65)":"rgba(239, 68, 68, 0.65)"}));try{a.current.setData(p),o.current.setData(v),n.current?.timeScale().fitContent(),l.current=!0}catch{}}else{const p=x[x.length-1];if(p.cvd!==void 0&&!isNaN(p.cvd))try{a.current.update({time:p.time,value:p.cvd})}catch{}if(p.delta!==void 0&&!isNaN(p.delta))try{o.current.update({time:p.time,value:p.delta,color:(p.delta||0)>=0?"rgba(16, 185, 129, 0.65)":"rgba(239, 68, 68, 0.65)"})}catch{}}},[s,e,t]);const h=s[s.length-1]?.cvd??0,u=h>=0;return r.jsxs("div",{className:"w-full rounded-2xl bg-[#090b0e] border border-border/80 overflow-hidden shadow-xl flex flex-col",children:[r.jsxs("div",{className:"px-4 py-2 bg-bg-card/80 border-b border-border/60 flex items-center justify-between text-xs font-mono",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-400"}),r.jsx("span",{className:"font-semibold text-text-primary text-[11px] tracking-wide",children:"Cumulative Volume Delta (CVD) & Bar Delta"})]}),r.jsxs("div",{className:"flex items-center gap-3 text-[11px]",children:[r.jsx("span",{className:"text-text-muted",children:"Net Cumulative:"}),r.jsx("span",{className:`font-bold ${u?"text-emerald-400":"text-rose-400"}`,title:`Exact CVD: ${h.toLocaleString()}`,children:Up(h)})]})]}),r.jsx("div",{ref:i,className:"w-full flex-1 min-h-[160px]"})]})}function sa(s){return!s||isNaN(s)||s<=0?"$0":s>=1e9?`$${(s/1e9).toFixed(2)}B`:s>=1e6?`$${(s/1e6).toFixed(2)}M`:s>=1e3?`$${(s/1e3).toFixed(1)}K`:`$${s.toFixed(2)}`}function Wp({candles:s,symbol:e,height:t=190,exchangesIncluded:i=["binance","bybit"]}){const n=y.useRef(null),a=y.useRef(null),o=y.useRef(null),l=y.useRef(!1),c=y.useRef(null),d=y.useRef(e);y.useEffect(()=>{if(!n.current)return;const f=xi(n.current,{width:n.current.clientWidth,height:t,layout:{background:{type:At.Solid,color:"#090b0e"},textColor:"#94a3b8",fontSize:10,fontFamily:"JetBrains Mono, ui-monospace, monospace"},grid:{vertLines:{color:"rgba(30, 41, 59, 0.3)",style:he.SparseDotted},horzLines:{color:"rgba(30, 41, 59, 0.3)",style:he.SparseDotted}},crosshair:{mode:Lt.Normal},rightPriceScale:{borderColor:"#1e293b",autoScale:!0},timeScale:{borderColor:"#1e293b",timeVisible:!0,secondsVisible:!1}});a.current=f;const g=f.addSeries(Lp,{topColor:"rgba(56, 189, 248, 0.35)",bottomColor:"rgba(56, 189, 248, 0.02)",lineColor:"#38bdf8",lineWidth:2,crosshairMarkerVisible:!0,priceFormat:{type:"custom",formatter:S=>sa(S)}});o.current=g;const p=()=>{n.current&&a.current&&a.current.applyOptions({width:n.current.clientWidth})};window.addEventListener("resize",p);const v=new ResizeObserver(p);return v.observe(n.current),()=>{window.removeEventListener("resize",p),v.disconnect(),f.remove(),a.current=null,o.current=null,l.current=!1,c.current=null}},[t]),y.useEffect(()=>{if(d.current!==e){d.current=e,c.current=null,l.current=!1;try{o.current?.setData([])}catch{}}},[e]),y.useEffect(()=>{if(!o.current)return;if(!s||s.length===0){l.current=!1,c.current=null;try{o.current.setData([])}catch{}return}const f=new Map;for(const k of s)k&&k.time&&!isNaN(k.time)&&f.set(k.time,k);const g=Array.from(f.values()).sort((k,C)=>k.time-C.time);if(g.length===0)return;const p=g.filter(k=>k.open_interest!==void 0&&k.open_interest!==null&&!isNaN(k.open_interest)&&k.open_interest>0).map(k=>({time:k.time,value:k.open_interest}));if(p.length===0){l.current=!1,c.current=null;try{o.current.setData([])}catch{}return}const v=p[0].time,S=c.current!==v;if(!l.current||S){c.current=v;try{o.current.setData(p),a.current?.timeScale().fitContent(),l.current=!0}catch{}}else{const k=p[p.length-1];try{o.current.update({time:k.time,value:k.value})}catch{}}},[s,e,t]);const h=s.map(f=>f.open_interest).filter(f=>typeof f=="number"&&f>0),u=h[h.length-1]??0,m=h[0]??0,x=m>0?(u-m)/m*100:0,b=x>=0;return r.jsxs("div",{className:"w-full rounded-2xl bg-[#090b0e] border border-border/80 overflow-hidden shadow-xl flex flex-col",children:[r.jsxs("div",{className:"px-4 py-2 bg-bg-card/80 border-b border-border/60 flex items-center justify-between text-xs font-mono",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-accent-blue animate-pulse"}),r.jsx("span",{className:"font-semibold text-text-primary text-[11px] tracking-wide",children:"Aggregated Open Interest (USD Notional)"}),r.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-bg-elevated text-text-muted border border-border/50 uppercase",children:i.join(" + ")})]}),r.jsxs("div",{className:"flex items-center gap-3 text-[11px]",children:[r.jsx("span",{className:"text-text-muted",children:"Total OI:"}),r.jsx("span",{className:"font-bold text-accent-blue",children:sa(u)}),h.length>1&&r.jsx("span",{className:`font-semibold px-1.5 py-0.2 rounded text-[10px] ${b?"bg-emerald-500/10 text-emerald-400":"bg-rose-500/10 text-rose-400"}`,children:b?`+${x.toFixed(2)}%`:`${x.toFixed(2)}%`})]})]}),r.jsx("div",{ref:n,className:"w-full flex-1 min-h-[170px]"})]})}function Hp({symbol:s,height:e=190}){const t=y.useRef(null),i=y.useRef(null),n=y.useRef(null),{data:a}=Zt({queryKey:["fundingHistory",s],queryFn:()=>Zi.getFundingHistory(s,40),staleTime:6e4,refetchInterval:6e4});y.useEffect(()=>{if(!t.current)return;const u=xi(t.current,{width:t.current.clientWidth,height:e,layout:{background:{type:At.Solid,color:"#090b0e"},textColor:"#94a3b8",fontSize:10,fontFamily:"JetBrains Mono, ui-monospace, monospace"},grid:{vertLines:{color:"rgba(30, 41, 59, 0.3)",style:he.SparseDotted},horzLines:{color:"rgba(30, 41, 59, 0.3)",style:he.SparseDotted}},crosshair:{mode:Lt.Normal},rightPriceScale:{borderColor:"#1e293b",autoScale:!0},timeScale:{borderColor:"#1e293b",timeVisible:!0,secondsVisible:!1}});i.current=u;const m=u.addSeries(Tr,{priceFormat:{type:"custom",formatter:f=>`${(f*100).toFixed(4)}%`}});n.current=m;const x=()=>{t.current&&i.current&&i.current.applyOptions({width:t.current.clientWidth})};window.addEventListener("resize",x);const b=new ResizeObserver(x);return b.observe(t.current),()=>{window.removeEventListener("resize",x),b.disconnect(),u.remove(),i.current=null,n.current=null}},[e]),y.useEffect(()=>{if(!n.current)return;if(!a?.history||a.history.length===0){try{n.current.setData([])}catch{}return}const u=a.history.filter(m=>m.avg_funding!==null&&!isNaN(m.avg_funding)).map(m=>{const x=m.avg_funding;return{time:m.time,value:x,color:x>=1e-4?"rgba(239, 68, 68, 0.75)":x>=0?"rgba(16, 185, 129, 0.65)":"rgba(56, 189, 248, 0.75)"}});try{n.current.setData(u),i.current?.timeScale().fitContent()}catch{}},[a,e]);const o=a?.history?.[a.history.length-1],l=o?.avg_funding??0,c=l*3*365*100,d=[];o?.binance!==void 0&&o?.binance!==null&&d.push("Binance"),o?.bybit!==void 0&&o?.bybit!==null&&d.push("Bybit"),o?.okx!==void 0&&o?.okx!==null&&d.push("OKX"),o?.bitget!==void 0&&o?.bitget!==null&&d.push("Bitget");const h=d.length>0?d.join(" + "):"Binance + Bybit + OKX + Bitget";return r.jsxs("div",{className:"w-full rounded-2xl bg-[#090b0e] border border-border/80 overflow-hidden shadow-xl flex flex-col",children:[r.jsxs("div",{className:"px-4 py-2 bg-bg-card/80 border-b border-border/60 flex items-center justify-between text-xs font-mono",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-purple-400"}),r.jsx("span",{className:"font-semibold text-text-primary text-[11px] tracking-wide",children:"Multi-Exchange Funding Rate History (8h Interval)"}),r.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-bg-elevated text-text-muted border border-border/50 uppercase",children:h})]}),r.jsxs("div",{className:"flex items-center gap-3 text-[11px]",children:[r.jsx("span",{className:"text-text-muted",children:"Current Rate:"}),r.jsxs("span",{className:`font-bold ${l>0?"text-emerald-400":l<0?"text-sky-400":"text-text-primary"}`,children:[(l*100).toFixed(4),"%"]}),r.jsxs("span",{className:"text-text-muted text-[10px]",children:["(APR: ",c>0?`+${c.toFixed(1)}%`:`${c.toFixed(1)}%`,")"]})]})]}),r.jsx("div",{ref:t,className:"w-full flex-1 min-h-[170px]"})]})}function Vp({data:s,symbol:e,isWsConnected:t}){const i=s?.exchanges,n=s?.ref_price||0,a=d=>d==null||d===0?"-":d>=1e3?`$${d.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`:d>=1?`$${d.toFixed(4)}`:d>=.01?`$${d.toFixed(6)}`:`$${d.toFixed(8)}`,o=d=>{if(d==null)return"-";const h=d*100,u=h<0;return r.jsx("span",{className:u?"text-emerald-400 font-semibold":Math.abs(h)>.03?"text-amber-400 font-semibold":"text-text-secondary",children:h>0?`+${h.toFixed(4)}%`:`${h.toFixed(4)}%`})},l=d=>d==null||d===0?"-":d>=1e9?`$${(d/1e9).toFixed(2)}B`:d>=1e6?`$${(d/1e6).toFixed(2)}M`:d>=1e3?`$${(d/1e3).toFixed(1)}K`:`$${d.toLocaleString()}`,c=[{id:"binance",name:"Binance USDⓈ-M",tag:"CEX Lead",info:i?.binance},{id:"bybit",name:"Bybit Linear",tag:"CEX Direct",info:i?.bybit},{id:"okx",name:"OKX Swap",tag:"CEX Global",info:i?.okx},{id:"bitget",name:"Bitget Mix",tag:"CEX Copy",info:i?.bitget},{id:"hyperliquid",name:"Hyperliquid",tag:"On-Chain DEX",info:i?.hyperliquid}];return r.jsxs("div",{className:"rounded-2xl bg-bg-card/95 border border-border/80 p-4 shadow-xl flex flex-col gap-3 font-mono",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border/60 pb-2.5",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Xs,{size:15,className:"text-accent-blue"}),r.jsxs("h3",{className:"text-xs font-bold text-text-primary tracking-wide uppercase",children:[e," Multi-Exchange Confluence"]})]}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("span",{className:`flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-semibold border ${t?"bg-emerald-500/10 text-emerald-400 border-emerald-500/30":"bg-amber-500/10 text-amber-400 border-amber-500/30"}`,children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-emerald-400 animate-pulse":"bg-amber-400"}`}),t?"Tick Stream (1.5s)":"Fast Polling"]})})]}),n>0&&r.jsxs("div",{className:"bg-bg-elevated/70 border border-border/50 rounded-xl p-2.5 flex items-center justify-between text-xs",children:[r.jsx("span",{className:"text-text-muted text-[11px]",children:"Aggregated Ref Mark Price:"}),r.jsx("span",{className:"font-bold text-text-primary text-sm tracking-wide text-sky-400",children:a(n)})]}),r.jsx("div",{className:"flex flex-col gap-2",children:c.map(d=>{const h=d.info?.available,u=d.info?.diff_pct,m=u!=null&&Math.abs(u)>=.1;return r.jsxs("div",{className:`p-2.5 rounded-xl border transition-all flex flex-col gap-1.5 ${h?"bg-bg-elevated/40 border-border/60 hover:border-accent-blue/40":"bg-bg-elevated/20 border-border/30 opacity-50"}`,children:[r.jsxs("div",{className:"flex items-center justify-between text-xs",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"font-semibold text-text-primary",children:d.name}),r.jsx("span",{className:"text-[9px] px-1.5 py-0.2 bg-bg-card border border-border rounded text-text-muted",children:d.tag})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"font-bold text-text-primary",children:a(d.info?.mark_price)}),u!=null&&r.jsx("span",{className:`text-[10px] px-1.5 py-0.2 rounded font-semibold ${m?"bg-amber-500/20 text-amber-300 border border-amber-500/40":u>0?"text-emerald-400":"text-rose-400"}`,children:u>0?`+${u}%`:`${u}%`})]})]}),h&&r.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[10px] text-text-muted pt-1 border-t border-border/30",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{children:"Funding (8h):"}),o(d.info?.funding_rate)]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{children:"Open Interest:"}),r.jsx("span",{className:"text-text-secondary font-medium",children:l(d.info?.open_interest)})]})]})]},d.id)})})]})}const Kp=[{id:"1m",label:"1m"},{id:"5m",label:"5m"},{id:"15m",label:"15m"},{id:"1h",label:"1H"},{id:"4h",label:"4H"},{id:"1d",label:"1D"}],Gp=[{id:"auto",label:"⚡ Aggregated (All)"},{id:"binance",label:"Binance"},{id:"bybit",label:"Bybit"},{id:"okx",label:"OKX"},{id:"bitget",label:"Bitget"}];function Qp({initialSymbol:s="BTCUSDT",onSelectSymbol:e,onNavigateToAI:t}){const{data:i=[]}=us(),{data:n=[]}=li(),a=y.useMemo(()=>i.filter(F=>F.is_active),[i]),[o,l]=y.useState(()=>s&&i.some(F=>F.symbol===s)?s:a[0]?.symbol||"BTCUSDT");y.useEffect(()=>{s&&l(s)},[s]);const[c,d]=y.useState("15m"),[h,u]=y.useState("auto"),[m,x]=y.useState(!0),[b,f]=y.useState(!0),[g,p]=y.useState(!0),[v,S]=y.useState("cvd"),[j,k]=y.useState(""),[C,E]=y.useState(!1),[T,D]=y.useState(!1),O=y.useMemo(()=>{if(!o)return;const F=o.toUpperCase().replace(/[/-]/g,"");return n.find(le=>(le.symbol||"").toUpperCase().replace(/[/-]/g,"")===F)},[n,o]),M=O?.trade_levels,L=O?.predictive?.liquidation_magnets,{candles:$,currentPrice:z,multiStream:V,isAggregated:q,exchangesIncluded:Z,isLoading:ae,isWsConnected:A,refetchCandles:H}=nu({symbol:o,timeframe:c,exchange:h,enabled:!0}),_=y.useMemo(()=>j.trim()?a.filter(F=>F.symbol.toLowerCase().includes(j.toLowerCase())||F.display_name.toLowerCase().includes(j.toLowerCase())):a,[a,j]),B=F=>F==null||F===0||isNaN(F)?"":F>=1e3?`$${F.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`:F>=1?`$${F.toFixed(4)}`:F>=.01?`$${F.toFixed(6)}`:`$${F.toFixed(8)}`,Y=y.useMemo(()=>{const F=(O?.symbol||"").toUpperCase().replace(/[/-]/g,""),le=(o||"").toUpperCase().replace(/[/-]/g,"");return!O||!le||F!==le?{showLevels:m,showMagnets:b}:{entryPrice:M?.entry_price,stopLoss:M?.stop_loss,takeProfit1:M?.take_profit_1,takeProfit2:M?.take_profit_2,upperMagnet:L?.upper_magnet,lowerMagnet:L?.lower_magnet,showLevels:m,showMagnets:b}},[O,o,M?.entry_price,M?.stop_loss,M?.take_profit_1,M?.take_profit_2,L?.upper_magnet,L?.lower_magnet,m,b]);return r.jsxs("div",{className:"flex-1 flex flex-col h-full overflow-hidden bg-bg-primary text-text-primary",children:[r.jsxs("div",{className:"px-4 py-2.5 bg-bg-card/95 border-b border-border/80 flex flex-wrap items-center justify-between gap-3 shadow-md z-20",children:[r.jsxs("div",{className:"flex items-center gap-3 relative",children:[r.jsxs("div",{className:"relative",children:[r.jsxs("button",{type:"button",onClick:()=>E(!C),className:"flex items-center gap-2 px-3 py-1.5 rounded-xl bg-bg-elevated border border-border/80 hover:border-accent-blue/50 text-xs font-mono font-bold transition-all shadow-sm active:scale-95",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-accent-blue animate-pulse"}),r.jsx("span",{className:"text-sm tracking-wide text-text-primary",children:o}),r.jsx("span",{className:"text-text-muted text-[10px]",children:"▼"})]}),C&&r.jsxs("div",{className:"absolute top-full left-0 mt-2 w-64 max-h-80 bg-bg-card border border-border/80 rounded-2xl shadow-2xl p-2 z-50 flex flex-col gap-1 backdrop-blur-xl",children:[r.jsxs("div",{className:"relative mb-1",children:[r.jsx(Zs,{size:14,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-text-muted"}),r.jsx("input",{type:"text",value:j,onChange:F=>k(F.target.value),placeholder:"Cari pair...",className:"w-full pl-8 pr-3 py-1.5 rounded-lg bg-bg-elevated text-xs font-mono border border-border/60 focus:border-accent-blue focus:outline-none",autoFocus:!0})]}),r.jsx("div",{className:"overflow-y-auto max-h-60 flex flex-col gap-0.5",children:_.map(F=>{const le=F.symbol===o;return r.jsxs("button",{type:"button",onClick:()=>{l(F.symbol),e?.(F.symbol),E(!1),k("")},className:`flex items-center justify-between px-3 py-2 rounded-xl text-xs font-mono transition-all text-left ${le?"bg-accent-blue/20 text-accent-blue font-bold border border-accent-blue/30":"hover:bg-bg-elevated text-text-secondary hover:text-text-primary"}`,children:[r.jsx("span",{children:F.display_name||F.symbol}),F.streak_count&&F.streak_count>1?r.jsxs("span",{className:"text-[10px] px-1.5 py-0.2 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30",children:[F.streak_count,"🔥"]}):null]},F.symbol)})})]})]}),r.jsxs("div",{className:"flex items-center gap-2 font-mono",children:[r.jsx("span",{className:"text-base sm:text-lg font-extrabold text-sky-400 tracking-tight",children:B(z)||"-"}),O&&r.jsx(hr,{direction:O.direction,size:"sm"})]})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("div",{className:"flex items-center bg-bg-elevated p-1 rounded-xl border border-border/70 shadow-inner",children:Kp.map(F=>r.jsx("button",{type:"button",onClick:()=>d(F.id),className:`px-2.5 py-1 rounded-lg text-xs font-mono font-medium transition-all ${c===F.id?"bg-accent-blue text-white shadow-sm font-bold":"text-text-secondary hover:text-text-primary"}`,children:F.label},F.id))}),r.jsx("div",{className:"hidden sm:flex items-center bg-bg-elevated p-1 rounded-xl border border-border/70 shadow-inner",children:Gp.map(F=>r.jsx("button",{type:"button",onClick:()=>u(F.id),className:`px-2 py-1 rounded-lg text-[11px] font-mono transition-all ${h===F.id?"bg-bg-card text-accent-blue font-bold border border-accent-blue/30 shadow-sm":"text-text-muted hover:text-text-secondary"}`,children:F.label},F.id))})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("button",{type:"button",onClick:()=>x(!m),title:"Toggle Trade Plan Levels (Entry, SL, TP)",className:`px-2.5 py-1.5 rounded-xl border text-xs font-mono flex items-center gap-1.5 transition-all active:scale-95 ${m?"bg-sky-500/15 border-sky-500/40 text-sky-300 font-semibold":"bg-bg-elevated border-border text-text-muted hover:text-text-secondary"}`,children:[m?r.jsx(Jo,{size:13}):r.jsx(Xo,{size:13}),r.jsx("span",{className:"hidden md:inline",children:"Levels"})]}),r.jsxs("button",{type:"button",onClick:()=>f(!b),title:"Toggle Liquidation Magnet Pools",className:`px-2.5 py-1.5 rounded-xl border text-xs font-mono flex items-center gap-1.5 transition-all active:scale-95 ${b?"bg-purple-500/15 border-purple-500/40 text-purple-300 font-semibold":"bg-bg-elevated border-border text-text-muted hover:text-text-secondary"}`,children:[r.jsx(cr,{size:13}),r.jsx("span",{className:"hidden md:inline",children:"Magnets"})]}),r.jsxs("button",{type:"button",onClick:()=>p(!g),title:"Toggle Sub-Chart Analytics (CVD, Aggregated OI, Funding History)",className:`px-2.5 py-1.5 rounded-xl border text-xs font-mono flex items-center gap-1.5 transition-all active:scale-95 ${g?"bg-amber-500/15 border-amber-500/40 text-amber-300 font-semibold":"bg-bg-elevated border-border text-text-muted hover:text-text-secondary"}`,children:[r.jsx(ot,{size:13}),r.jsx("span",{className:"hidden md:inline",children:"Analytics"})]}),r.jsx("button",{type:"button",onClick:()=>H(),title:"Refresh Data Chart",className:"p-1.5 rounded-xl bg-bg-elevated border border-border hover:border-accent-blue text-text-secondary hover:text-text-primary transition-all active:scale-95",children:r.jsx(Pe,{size:14,className:ae?"animate-spin text-accent-blue":""})}),t&&r.jsxs("button",{type:"button",onClick:()=>t(o),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-purple-600/20 hover:bg-purple-600/30 text-purple-300 border border-purple-500/40 text-xs font-mono font-semibold transition-all active:scale-95",children:[r.jsx(Be,{size:13}),r.jsx("span",{className:"hidden lg:inline",children:"Tanya Damian"})]}),r.jsxs("button",{type:"button",onClick:()=>D(!0),className:"flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-400 hover:to-amber-500 text-black font-bold text-xs font-mono shadow-md shadow-amber-500/20 transition-all active:scale-95",children:[r.jsx(Oe,{size:14,className:"fill-black"}),r.jsx("span",{children:"Eksekusi"})]})]})]}),r.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row overflow-hidden relative",children:[r.jsxs("div",{className:"flex-1 flex flex-col p-3 overflow-y-auto gap-3",children:[r.jsx("div",{className:"flex-1 min-h-[400px] flex flex-col",children:r.jsx(Fp,{candles:$,symbol:o,overlays:Y,height:g?400:580,isLoading:ae})}),g&&r.jsxs("div",{className:"flex flex-col gap-2 shrink-0",children:[r.jsxs("div",{className:"flex items-center justify-between px-1",children:[r.jsxs("div",{className:"flex items-center gap-1 bg-bg-card p-1 rounded-xl border border-border/80 shadow-inner",children:[r.jsxs("button",{type:"button",onClick:()=>S("cvd"),className:`flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-mono font-semibold transition-all ${v==="cvd"?"bg-amber-500/15 text-amber-300 border border-amber-500/40 shadow-sm":"text-text-muted hover:text-text-secondary"}`,children:[r.jsx(ot,{size:12}),r.jsx("span",{children:"Aggregated CVD"})]}),r.jsxs("button",{type:"button",onClick:()=>S("oi"),className:`flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-mono font-semibold transition-all ${v==="oi"?"bg-sky-500/15 text-sky-300 border border-sky-500/40 shadow-sm":"text-text-muted hover:text-text-secondary"}`,children:[r.jsx(Je,{size:12}),r.jsx("span",{children:"Aggregated OI ($)"})]}),r.jsxs("button",{type:"button",onClick:()=>S("funding"),className:`flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-mono font-semibold transition-all ${v==="funding"?"bg-purple-500/15 text-purple-300 border border-purple-500/40 shadow-sm":"text-text-muted hover:text-text-secondary"}`,children:[r.jsx(Zo,{size:12}),r.jsx("span",{children:"Funding History"})]})]}),q&&r.jsxs("div",{className:"hidden sm:flex items-center gap-1.5 text-[10px] font-mono text-text-muted px-2.5 py-1 rounded-xl bg-bg-card border border-border/70",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"}),r.jsxs("span",{children:["Aggregated: ",Z.join(" + ").toUpperCase()]})]})]}),r.jsxs("div",{className:"h-[185px]",children:[v==="cvd"&&r.jsx(qp,{candles:$,symbol:o,height:185}),v==="oi"&&r.jsx(Wp,{candles:$,symbol:o,height:185,exchangesIncluded:Z}),v==="funding"&&r.jsx(Hp,{symbol:o,height:185})]})]})]}),r.jsxs("div",{className:"w-full lg:w-80 xl:w-96 border-t lg:border-t-0 lg:border-l border-border/80 bg-bg-card/70 p-3 overflow-y-auto flex flex-col gap-3 font-mono text-xs",children:[r.jsxs("div",{className:"p-3.5 rounded-2xl bg-bg-elevated/80 border border-border/80 flex flex-col gap-2.5 shadow-lg",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border/60 pb-2",children:[r.jsxs("span",{className:"font-bold text-text-primary text-[11px] uppercase tracking-wide flex items-center gap-1.5",children:[r.jsx(el,{size:13,className:"text-accent-blue"}),"Signal Trade Levels"]}),M?.risk_reward&&r.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-accent-blue/15 text-accent-blue border border-accent-blue/30 font-bold",children:["R:R ",M.risk_reward]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[11px]",children:[r.jsxs("div",{className:"p-2 rounded-xl bg-bg-card border border-sky-500/20 flex flex-col",children:[r.jsx("span",{className:"text-[10px] text-text-muted",children:"Entry Zone:"}),r.jsx("span",{className:"font-bold text-sky-400",children:M?.entry_zone||B(M?.entry_price)||"-"})]}),r.jsxs("div",{className:"p-2 rounded-xl bg-bg-card border border-rose-500/20 flex flex-col",children:[r.jsx("span",{className:"text-[10px] text-text-muted",children:"Stop Loss:"}),r.jsx("span",{className:"font-bold text-rose-400",children:M?.stop_loss_str||B(M?.stop_loss)||"-"})]}),r.jsxs("div",{className:"p-2 rounded-xl bg-bg-card border border-emerald-500/20 flex flex-col",children:[r.jsx("span",{className:"text-[10px] text-text-muted",children:"Take Profit 1:"}),r.jsx("span",{className:"font-bold text-emerald-400",children:M?.take_profit_1_str||B(M?.take_profit_1)||"-"})]}),r.jsxs("div",{className:"p-2 rounded-xl bg-bg-card border border-emerald-500/20 flex flex-col",children:[r.jsx("span",{className:"text-[10px] text-text-muted",children:"Take Profit 2:"}),r.jsx("span",{className:"font-bold text-emerald-300",children:M?.take_profit_2_str||B(M?.take_profit_2)||"-"})]})]})]}),L&&r.jsxs("div",{className:"p-3.5 rounded-2xl bg-bg-elevated/80 border border-purple-500/30 flex flex-col gap-2.5 shadow-lg",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border/60 pb-2",children:[r.jsxs("span",{className:"font-bold text-purple-300 text-[11px] uppercase tracking-wide flex items-center gap-1.5",children:[r.jsx(ts,{size:13,className:"text-purple-400"}),"Liquidation Magnet Pools"]}),r.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-purple-500/20 text-purple-300 border border-purple-500/40 font-bold",children:["Pull: ",L.dist_upper_pct!=null&&L.dist_lower_pct!=null&&Math.abs(L.dist_upper_pct)<=Math.abs(L.dist_lower_pct)?"UPPER":"LOWER"]})]}),r.jsxs("div",{className:"flex flex-col gap-1.5 text-[11px]",children:[r.jsxs("div",{className:"flex items-center justify-between p-2 rounded-xl bg-bg-card border border-border/50",children:[r.jsx("span",{className:"text-text-muted",children:"Upper Magnet (Short Liq):"}),r.jsxs("div",{className:"flex items-center gap-1.5 font-bold",children:[r.jsx("span",{className:"text-text-primary",children:L.upper_magnet_str||B(L.upper_magnet)}),r.jsxs("span",{className:"text-purple-400 text-[10px]",children:["(",L.dist_upper_pct>0?`+${L.dist_upper_pct}%`:`${L.dist_upper_pct}%`,")"]})]})]}),r.jsxs("div",{className:"flex items-center justify-between p-2 rounded-xl bg-bg-card border border-border/50",children:[r.jsx("span",{className:"text-text-muted",children:"Lower Magnet (Long Liq):"}),r.jsxs("div",{className:"flex items-center gap-1.5 font-bold",children:[r.jsx("span",{className:"text-text-primary",children:L.lower_magnet_str||B(L.lower_magnet)}),r.jsxs("span",{className:"text-purple-400 text-[10px]",children:["(",L.dist_lower_pct,"%)"]})]})]})]})]}),r.jsx(Vp,{data:V,symbol:o,isWsConnected:A})]})]}),T&&r.jsx(Qa,{isOpen:T,onClose:()=>D(!1),symbol:o,summary:{bias:O?.direction||"NEUTRAL",verdictSummary:`Setup ${O?.direction||"NEUTRAL"} untuk ${o}`,entryZone:M?.entry_zone||B(M?.entry_price)||B(z)||"",stopLoss:M?.stop_loss_str||B(M?.stop_loss)||"",takeProfit1:M?.take_profit_1_str||B(M?.take_profit_1)||"",takeProfit2:M?.take_profit_2_str||B(M?.take_profit_2)||"",takeProfitRaw:`${M?.take_profit_1_str||""} / ${M?.take_profit_2_str||""}`,leverage:"3x",riskReward:M?.risk_reward||"1:2",invalidation:"-",liquidationMagnet:L?.upper_magnet_str||"-",flowStatus:"Active"},markPrice:z,onExecutionSuccess:()=>window.dispatchEvent(new CustomEvent("journal-updated"))})]})}function Yp(){const[s,e]=y.useState(!1),t=y.useRef(null),{data:i=[]}=us(),{data:n=[]}=li();y.useEffect(()=>{function o(l){t.current&&!t.current.contains(l.target)&&e(!1)}return s&&document.addEventListener("mousedown",o),()=>{document.removeEventListener("mousedown",o)}},[s]);const a=y.useMemo(()=>{const o=new Set(i.filter(M=>M.is_active).map(M=>M.symbol)),l=n.filter(M=>o.has(M.symbol)),c=l.length;if(c===0)return null;const d=l.filter(M=>M.direction==="LONG"),h=l.filter(M=>M.direction==="SHORT"),u=l.filter(M=>M.direction==="NEUTRAL"),m=d.length,x=h.length,b=u.length,f=Math.round(m/c*100),g=Math.round(x/c*100),p=Math.max(0,100-f-g),v=m?(d.reduce((M,R)=>M+R.conviction,0)/m).toFixed(1):"0.0",S=x?(h.reduce((M,R)=>M+R.conviction,0)/x).toFixed(1):"0.0";let j="NEUTRAL",k="Netral / Chop",C="text-text-muted",E="bg-text-muted",T="bg-bg-elevated/80",D="border-border",O="Pasar seimbang / sideways. Gunakan ukuran posisi terukur dan pasang SL ketat.";return m>=x*1.3&&f>=35?(j="BULLISH",k=f>=50?"Strong Bullish":"Bullish Bias",C="text-signal-long",E="bg-signal-long",T="bg-signal-long/10",D="border-signal-long/30",O="Pasar condong akumulasi beli. Prioritaskan setup LONG saat terjadi pullback di support."):x>=m*1.3&&g>=35&&(j="BEARISH",k=g>=50?"Strong Bearish":"Bearish Bias",C="text-signal-short",E="bg-signal-short",T="bg-signal-short/10",D="border-signal-short/30",O="Pasar condong tekanan jual. Prioritaskan setup SHORT di resistensi dan hindari kejar pucuk."),{total:c,longCount:m,shortCount:x,neutralCount:b,longPct:f,shortPct:g,neutralPct:p,avgLongConv:v,avgShortConv:S,regime:j,regimeLabel:k,textColor:C,dotColor:E,badgeBg:T,badgeBorder:D,guide:O}},[i,n]);return a?r.jsxs("div",{className:"relative shrink-0",ref:t,children:[r.jsxs("button",{type:"button",onClick:()=>e(!s),className:`flex items-center gap-1.5 sm:gap-2 px-2.5 sm:px-3 py-1 sm:py-1.5 rounded-full border text-xs font-mono transition-all shadow-sm cursor-pointer select-none active:scale-95 ${a.badgeBg} ${a.badgeBorder} hover:border-accent-blue/50`,title:`Global Market: ${a.regimeLabel} (${a.total} pair)`,children:[r.jsx("span",{className:`w-2 h-2 rounded-full ${a.dotColor} animate-pulse shrink-0`}),a.regime==="BULLISH"&&r.jsx(Je,{size:13,className:"text-signal-long shrink-0"}),a.regime==="BEARISH"&&r.jsx(Ct,{size:13,className:"text-signal-short shrink-0"}),a.regime==="NEUTRAL"&&r.jsx(ia,{size:13,className:"text-text-muted shrink-0"}),r.jsx("span",{className:`font-bold uppercase tracking-tight text-[11px] ${a.textColor}`,children:a.regime}),r.jsxs("div",{className:"hidden lg:flex w-14 h-1.5 rounded-full bg-bg-primary overflow-hidden border border-border/40 shrink-0",children:[r.jsx("div",{style:{width:`${a.longPct}%`},className:"bg-signal-long h-full",title:`Bullish: ${a.longPct}%`}),r.jsx("div",{style:{width:`${a.neutralPct}%`},className:"bg-text-muted/30 h-full",title:`Neutral: ${a.neutralPct}%`}),r.jsx("div",{style:{width:`${a.shortPct}%`},className:"bg-signal-short h-full",title:`Bearish: ${a.shortPct}%`})]}),r.jsxs("span",{className:"hidden sm:inline text-[10px] text-text-secondary font-medium",children:[a.longCount,"L / ",a.shortCount,"S"]}),r.jsx(_t,{size:11,className:`text-text-muted transition-transform ${s?"rotate-180":""}`})]}),s&&r.jsxs("div",{className:"absolute right-0 sm:left-auto top-full mt-2 w-72 sm:w-80 rounded-xl bg-bg-card/95 backdrop-blur-md border border-border shadow-2xl p-3.5 z-50 text-xs animate-in fade-in zoom-in-95 duration-150",children:[r.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-border/60",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx(ot,{size:14,className:"text-accent-blue"}),r.jsxs("span",{className:"font-bold font-mono text-text-primary text-xs uppercase tracking-wide",children:["Global Sentiment (",a.total," Pair)"]})]}),r.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-mono font-bold uppercase border ${a.regime==="BULLISH"?"bg-signal-long/15 text-signal-long border-signal-long/30":a.regime==="BEARISH"?"bg-signal-short/15 text-signal-short border-signal-short/30":"bg-bg-elevated text-text-muted border-border"}`,children:a.regimeLabel})]}),r.jsxs("div",{className:"mt-3 space-y-2 font-mono text-[11px]",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex justify-between items-center mb-1",children:[r.jsx("span",{className:"text-signal-long font-semibold flex items-center gap-1",children:"🟢 Bullish (LONG):"}),r.jsxs("span",{className:"text-text-primary font-bold",children:[a.longCount," pair (",a.longPct,"%)"]})]}),r.jsx("div",{className:"w-full h-1.5 rounded-full bg-bg-primary overflow-hidden",children:r.jsx("div",{style:{width:`${a.longPct}%`},className:"h-full bg-signal-long rounded-full"})})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex justify-between items-center mb-1",children:[r.jsx("span",{className:"text-signal-short font-semibold flex items-center gap-1",children:"🔴 Bearish (SHORT):"}),r.jsxs("span",{className:"text-text-primary font-bold",children:[a.shortCount," pair (",a.shortPct,"%)"]})]}),r.jsx("div",{className:"w-full h-1.5 rounded-full bg-bg-primary overflow-hidden",children:r.jsx("div",{style:{width:`${a.shortPct}%`},className:"h-full bg-signal-short rounded-full"})})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex justify-between items-center mb-1",children:[r.jsx("span",{className:"text-text-muted font-medium flex items-center gap-1",children:"⚪ Netral (SIDEWAYS):"}),r.jsxs("span",{className:"text-text-secondary",children:[a.neutralCount," pair (",a.neutralPct,"%)"]})]}),r.jsx("div",{className:"w-full h-1.5 rounded-full bg-bg-primary overflow-hidden",children:r.jsx("div",{style:{width:`${a.neutralPct}%`},className:"h-full bg-text-muted/40 rounded-full"})})]})]}),r.jsxs("div",{className:"mt-3 pt-2.5 border-t border-border/40 grid grid-cols-2 gap-2 text-[10px] font-mono text-center",children:[r.jsxs("div",{className:"bg-bg-elevated/50 p-1.5 rounded-lg border border-border/40",children:[r.jsx("span",{className:"text-text-muted block text-[9px] uppercase",children:"Rerata Conv Long"}),r.jsxs("span",{className:"font-bold text-signal-long text-xs",children:[a.avgLongConv," / 10"]})]}),r.jsxs("div",{className:"bg-bg-elevated/50 p-1.5 rounded-lg border border-border/40",children:[r.jsx("span",{className:"text-text-muted block text-[9px] uppercase",children:"Rerata Conv Short"}),r.jsxs("span",{className:"font-bold text-signal-short text-xs",children:[a.avgShortConv," / 10"]})]})]}),r.jsxs("div",{className:"mt-2.5 p-2 rounded-lg bg-accent-blue/10 border border-accent-blue/20 text-[10px] flex items-start gap-1.5",children:[r.jsx(tl,{size:12,className:"text-accent-blue shrink-0 mt-0.5"}),r.jsx("p",{className:"text-text-secondary leading-snug",children:a.guide})]})]})]}):r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-bg-elevated/60 border border-border text-[11px] font-mono text-text-muted shrink-0",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-blue animate-pulse"}),r.jsx("span",{className:"hidden sm:inline",children:"Global: Syncing..."}),r.jsx("span",{className:"sm:hidden",children:"Sync..."})]})}const Jp=y.lazy(()=>xt(()=>import("./GlobalAISettingsModal-BOzCh0qM.js"),__vite__mapDeps([5,1,2,3])).then(s=>({default:s.GlobalAISettingsModal}))),Xp=y.lazy(()=>xt(()=>import("./ServerSettingsModal-B2vOj2j4.js"),__vite__mapDeps([6,1,2,3])).then(s=>({default:s.ServerSettingsModal})));function Zp({status:s,onClick:e}){const t={connected:{color:"text-signal-long",bg:"border-signal-long/20 bg-signal-long-bg",dot:"bg-signal-long animate-pulse",label:"Live",tooltip:Qe()?"Koneksi real-time aktif (WebSocket Live)":"Koneksi real-time aktif (HTTP Fast Polling)",icon:r.jsx(il,{size:12})},connecting:{color:"text-accent-yellow",bg:"border-accent-yellow/20 bg-yellow-500/10",dot:"bg-accent-yellow animate-pulse",label:"Sync...",tooltip:"Menghubungkan ke server pasar...",icon:r.jsx(Pe,{size:12,className:"animate-spin"})},disconnected:{color:"text-amber-400",bg:"border-amber-500/25 bg-amber-500/10",dot:"bg-amber-400 animate-pulse",label:"Sync",tooltip:"Koneksi terputus. Mencoba rekoneksi otomatis...",icon:r.jsx(Pe,{size:12,className:"animate-spin"})},error:{color:"text-signal-short",bg:"border-signal-short/20 bg-signal-short-bg",dot:"bg-signal-short",label:"Offline",tooltip:"Koneksi ke backend server terputus",icon:r.jsx(Pe,{size:12})}}[s];return r.jsxs("button",{type:"button",onClick:e,title:`${t.tooltip} (Klik untuk pengaturan server)`,className:`flex items-center gap-1.5 px-2 sm:px-3 py-1 sm:py-1.5 rounded-full border text-[11px] font-medium shrink-0 cursor-pointer hover:opacity-90 active:scale-95 transition-all ${t.bg} ${t.color}`,children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t.dot}`}),t.icon,r.jsx("span",{className:"hidden xs:inline",children:t.label})]})}function ef(s){return s.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}function tf({wsStatus:s,lastUpdated:e,onOpenMobileDrawer:t,onOpenAISettings:i,activePairCount:n=0,activeTab:a="signals",onTabChange:o}){const[l,c]=y.useState(!1),[d,h]=y.useState(!1),{settings:u,isConfigured:m}=ci(),x=()=>{i?i():c(!0)},b=u.provider==="vikey"?"Vikey":u.provider==="gemini"?"Gemini":u.provider==="openai"?"OpenAI":u.provider==="openrouter"?"OpenRouter":u.provider==="groq"?"Groq":"Custom",f=u.model.includes("/")?u.model.split("/")[1]:u.model;return r.jsxs(r.Fragment,{children:[r.jsxs("header",{className:"h-14 flex items-center justify-between px-3 sm:px-5 border-b border-border bg-bg-card shrink-0 gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2 sm:gap-2.5",children:[t&&a==="signals"&&r.jsxs("button",{type:"button",onClick:t,className:"md:hidden p-2 rounded-lg bg-bg-elevated/80 border border-border text-text-secondary hover:text-text-primary hover:border-accent-blue/40 flex items-center gap-1.5 transition-all shrink-0 active:scale-95",title:"Buka Daftar Trading Pairs",children:[r.jsx(sl,{size:16,className:"text-accent-blue"}),n>0&&r.jsx("span",{className:"text-[10px] font-mono font-bold bg-accent-blue/20 text-accent-blue px-1 rounded",children:n})]}),r.jsx("div",{className:"w-8 h-8 rounded-lg bg-accent-blue/20 border border-accent-blue/30 flex items-center justify-center shrink-0",children:r.jsx(Oe,{size:16,className:"text-accent-blue"})}),r.jsxs("div",{children:[r.jsx("h1",{className:"text-sm font-bold text-text-primary font-mono tracking-tight leading-none",children:"PerpsAI"}),r.jsx("p",{className:"text-[9px] sm:text-[10px] text-text-muted leading-none mt-0.5",children:"Signal & AI Terminal"})]})]}),o&&r.jsxs("div",{className:"hidden md:flex items-center bg-bg-elevated/90 p-1 rounded-xl border border-border shrink-0 shadow-inner",children:[r.jsxs("button",{type:"button",onClick:()=>o("signals"),className:`flex items-center gap-1.5 px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${a==="signals"?"bg-accent-blue text-white shadow-sm shadow-accent-blue/30":"text-text-secondary hover:text-text-primary"}`,children:[r.jsx(ei,{size:13}),r.jsx("span",{children:"Live Sinyal"})]}),r.jsxs("button",{type:"button",onClick:()=>o("chart"),className:`flex items-center gap-1.5 px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${a==="chart"?"bg-sky-600 text-white shadow-sm shadow-sky-600/30 font-bold":"text-text-secondary hover:text-sky-300"}`,children:[r.jsx(ot,{size:13}),r.jsx("span",{children:"Live Chart"})]}),r.jsxs("button",{type:"button",onClick:()=>o("ai"),className:`flex items-center gap-1.5 px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${a==="ai"?"bg-purple-600 text-white shadow-sm shadow-purple-600/30":"text-text-secondary hover:text-purple-300"}`,children:[r.jsx(Be,{size:13}),r.jsx("span",{children:"Damian"})]}),r.jsxs("button",{type:"button",onClick:()=>o("journal"),className:`flex items-center gap-1.5 px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${a==="journal"?"bg-emerald-600 text-white shadow-sm shadow-emerald-600/30":"text-text-secondary hover:text-emerald-300"}`,children:[r.jsx(la,{size:13}),r.jsx("span",{children:"Jurnal Trade"})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2.5",children:[r.jsx(Yp,{}),r.jsxs("button",{type:"button",onClick:x,className:`hidden sm:flex items-center gap-1.5 sm:gap-2 px-2.5 sm:px-3 py-1 sm:py-1.5 rounded-full border text-xs transition-all shadow-sm cursor-pointer shrink-0 ${m?"bg-purple-500/10 hover:bg-purple-500/20 border-purple-500/30 hover:border-purple-400 text-purple-200":"bg-amber-500/10 hover:bg-amber-500/20 border-amber-500/30 text-amber-200 animate-pulse"}`,title:"Klik untuk konfigurasi model AI dan API Key Universal",children:[r.jsx(Be,{size:13,className:m?"text-purple-400":"text-amber-400"}),r.jsx("span",{className:"font-semibold text-[11px]",children:m?r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"text-purple-300 font-mono hidden xs:inline",children:[b,":"]})," ",r.jsx("span",{className:"text-text-primary truncate max-w-[70px] xs:max-w-[100px] sm:max-w-[120px] inline-block align-bottom font-mono",children:f})]}):r.jsx("span",{className:"font-mono",children:"Atur AI"})}),r.jsx(dr,{size:11,className:"text-text-muted hover:text-text-primary hidden sm:inline"})]}),e&&r.jsxs("div",{className:"hidden lg:flex items-center gap-1.5 text-[11px] text-text-muted",children:[r.jsx(Fs,{size:11}),r.jsx("span",{children:ef(e)})]}),r.jsx(Zp,{status:s,onClick:()=>h(!0)})]})]}),d&&r.jsx(y.Suspense,{fallback:null,children:r.jsx(Xp,{isOpen:d,onClose:()=>h(!1)})}),!i&&l&&r.jsx(y.Suspense,{fallback:null,children:r.jsx(Jp,{isOpen:l,onClose:()=>c(!1)})})]})}function sf({activeTab:s,onTabChange:e,onOpenMobileDrawer:t,onOpenAISettings:i,activePairCount:n,isAIConfigured:a}){return r.jsxs("nav",{className:"md:hidden fixed bottom-0 left-0 right-0 z-40 bg-bg-card/95 backdrop-blur-md border-t border-border/80 flex items-center justify-around px-1 pt-1 pb-[max(0.35rem,env(safe-area-inset-bottom))] shadow-2xl","aria-label":"Mobile Navigation",children:[r.jsxs("button",{type:"button",onClick:()=>e("signals"),className:`flex-1 flex flex-col items-center justify-center py-1 px-0.5 rounded-xl transition-all duration-150 active:scale-95 min-h-[44px] ${s==="signals"?"text-accent-blue font-semibold":"text-text-muted hover:text-text-secondary"}`,children:[r.jsxs("div",{className:"relative",children:[r.jsx(ei,{size:18,className:s==="signals"?"animate-pulse":""}),s==="signals"&&r.jsx("span",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-accent-blue"})]}),r.jsx("span",{className:"text-[10px] font-medium tracking-tight mt-0.5",children:"Sinyal"})]}),r.jsxs("button",{type:"button",onClick:()=>e("chart"),className:`flex-1 flex flex-col items-center justify-center py-1 px-0.5 rounded-xl transition-all duration-150 active:scale-95 min-h-[44px] ${s==="chart"?"text-sky-400 font-semibold":"text-text-muted hover:text-text-secondary"}`,children:[r.jsxs("div",{className:"relative",children:[r.jsx(ot,{size:18}),s==="chart"&&r.jsx("span",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-sky-400"})]}),r.jsx("span",{className:"text-[10px] font-medium tracking-tight mt-0.5",children:"Chart"})]}),r.jsxs("button",{type:"button",onClick:()=>e("ai"),className:`flex-1 flex flex-col items-center justify-center py-1 px-0.5 rounded-xl transition-all duration-150 active:scale-95 min-h-[44px] ${s==="ai"?"text-purple-400 font-semibold":"text-text-muted hover:text-text-secondary"}`,children:[r.jsxs("div",{className:"relative",children:[r.jsx(Be,{size:18}),s==="ai"&&r.jsx("span",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-purple-400"})]}),r.jsx("span",{className:"text-[10px] font-medium tracking-tight mt-0.5",children:"Damian"})]}),r.jsxs("button",{type:"button",onClick:()=>e("journal"),className:`flex-1 flex flex-col items-center justify-center py-1 px-0.5 rounded-xl transition-all duration-150 active:scale-95 min-h-[44px] ${s==="journal"?"text-emerald-400 font-semibold":"text-text-muted hover:text-text-secondary"}`,children:[r.jsxs("div",{className:"relative",children:[r.jsx(la,{size:18}),s==="journal"&&r.jsx("span",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-emerald-400"})]}),r.jsx("span",{className:"text-[10px] font-medium tracking-tight mt-0.5",children:"Jurnal"})]}),r.jsxs("button",{type:"button",onClick:t,className:"flex-1 flex flex-col items-center justify-center py-1 px-0.5 rounded-xl text-text-muted hover:text-text-primary transition-all duration-150 active:scale-95 min-h-[44px]",children:[r.jsxs("div",{className:"relative",children:[r.jsx(Xs,{size:18}),n>0&&r.jsx("span",{className:"absolute -top-1 -right-2 px-1 py-0.2 bg-accent-blue/20 text-accent-blue border border-accent-blue/40 text-[9px] font-mono font-bold rounded-full leading-none",children:n})]}),r.jsx("span",{className:"text-[10px] font-medium tracking-tight mt-0.5",children:"Pairs"})]}),r.jsxs("button",{type:"button",onClick:i,className:"flex-1 flex flex-col items-center justify-center py-1 px-0.5 rounded-xl text-text-muted hover:text-text-primary transition-all duration-150 active:scale-95 min-h-[44px]",children:[r.jsxs("div",{className:"relative",children:[a?r.jsx(Fe,{size:18,className:"text-purple-400"}):r.jsx(dr,{size:18,className:"text-amber-400 animate-pulse"}),r.jsx("span",{className:`absolute -top-0.5 -right-1 w-1.5 h-1.5 rounded-full ${a?"bg-signal-long":"bg-amber-400 animate-ping"}`})]}),r.jsx("span",{className:"text-[10px] font-medium tracking-tight mt-0.5",children:"Atur AI"})]})]})}const rf=3e4,nf=1e3;function af(){const[s,e]=y.useState(()=>Qe()?"connecting":"connected"),[t,i]=y.useState(()=>Qe()?null:new Date),n=y.useRef(null),a=y.useRef(0),o=y.useRef(null),l=y.useRef(!0),c=y.useRef(0),d=os(),h=y.useRef(null),u=y.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null),h.current&&(clearInterval(h.current),h.current=null)},[]),m=y.useCallback(g=>{if(g){g.onopen=null,g.onmessage=null,g.onclose=null,g.onerror=null;try{g.close()}catch{}}},[]),x=y.useCallback(()=>{if(!l.current)return;u(),n.current&&(m(n.current),n.current=null);const g=Qe();if(!g){e("connected"),i(new Date);return}try{e("connecting");const p=new WebSocket(g);n.current=p,p.onopen=()=>{!l.current||n.current!==p||(e("connected"),a.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{n.current===p&&p.readyState===WebSocket.OPEN&&p.send(JSON.stringify({type:"ping"}))},2e4))},p.onmessage=v=>{if(!(!l.current||n.current!==p))try{const S=JSON.parse(v.data);if(S.type==="signal_update"&&S.data){const j=S.data,k=Date.now();k-c.current>3e3&&(c.current=k,i(new Date)),d.setQueryData(ht,C=>{if(!C)return[j];const E=C.findIndex(D=>D.symbol===j.symbol);if(E===-1)return[...C,j];const T=[...C];return T[E]=j,T}),d.setQueryData([...ht,j.symbol],j)}if((S.type==="pair_updated"||S.type==="pair_update")&&S.data){const j=S.data;d.setQueryData(ai,k=>k?k.map(C=>C.symbol===j.symbol?{...C,...j}:C):[j])}(S.type==="journal_updated"||S.type==="journal_update")&&S.data&&window.dispatchEvent(new CustomEvent("journal-updated",{detail:S.data}))}catch{}},p.onclose=()=>{n.current===p&&(h.current&&(clearInterval(h.current),h.current=null),n.current=null,l.current&&(e("disconnected"),b()))},p.onerror=()=>{n.current===p&&(h.current&&(clearInterval(h.current),h.current=null),l.current&&(e("error"),p.close()))}}catch{if(h.current&&(clearInterval(h.current),h.current=null),!l.current)return;e("error"),b()}},[u,m,d]),b=y.useCallback(()=>{if(!l.current||!Qe())return;o.current&&(clearTimeout(o.current),o.current=null);const g=Math.min(nf*Math.pow(2,a.current),rf);a.current++,o.current=setTimeout(()=>{o.current=null,l.current&&x()},g)},[x]);y.useEffect(()=>{l.current=!0,x();const g=()=>{u(),n.current&&(m(n.current),n.current=null),a.current=0,x()};return window.addEventListener("perps_server_url_changed",g),()=>{l.current=!1,window.removeEventListener("perps_server_url_changed",g),u(),n.current&&(m(n.current),n.current=null)}},[u,x,m]);const f=y.useCallback(()=>{u(),n.current&&(m(n.current),n.current=null),e("disconnected")},[u,m]);return{status:s,lastUpdated:t,disconnect:f}}const of=y.lazy(()=>xt(()=>import("./GlobalAISettingsModal-BOzCh0qM.js"),__vite__mapDeps([5,1,2,3])).then(s=>({default:s.GlobalAISettingsModal}))),lf=new Lo({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:2}}});function cf(){const[s,e]=y.useState("signals"),[t,i]=y.useState("BTCUSDT"),[n,a]=y.useState("BTCUSDT"),[o,l]=y.useState(!1),[c,d]=y.useState(!1),{status:h,lastUpdated:u}=af(),{data:m=[]}=us(),{isConfigured:x}=ci(),b=m.filter(v=>v.is_active).length,f=y.useCallback(v=>{i(v),e("chart")},[]),g=y.useCallback(v=>{a(v),e("ai")},[]),p=y.useCallback(()=>{e(v=>v!=="signals"?"signals":v),l(!0)},[]);return r.jsxs("div",{className:"flex flex-col h-screen bg-bg-primary overflow-hidden relative",children:[r.jsx(tf,{wsStatus:h,lastUpdated:u,activePairCount:b,activeTab:s,onTabChange:e,onOpenMobileDrawer:()=>l(!0),onOpenAISettings:()=>d(!0)}),r.jsx("div",{className:s==="signals"?"flex flex-1 overflow-hidden":"hidden",children:r.jsx(Ih,{onNavigateToAI:g,onNavigateToChart:f,isMobileDrawerOpen:o,setIsMobileDrawerOpen:l})}),r.jsx("div",{className:s==="chart"?"flex flex-1 overflow-hidden":"hidden",children:r.jsx(Qp,{initialSymbol:t,onSelectSymbol:i,onNavigateToAI:g})}),r.jsx("div",{className:s==="ai"?"flex flex-1 overflow-hidden":"hidden",children:r.jsx(su,{initialSymbol:n,onSelectSymbol:a})}),r.jsx("div",{className:s==="journal"?"flex flex-1 overflow-hidden":"hidden",children:r.jsx(ru,{onNavigateToAI:g,isActiveTab:s==="journal"})}),r.jsx(sf,{activeTab:s,onTabChange:e,onOpenMobileDrawer:p,onOpenAISettings:()=>d(!0),activePairCount:b,isAIConfigured:x}),c&&r.jsx(y.Suspense,{fallback:null,children:r.jsx(of,{isOpen:c,onClose:()=>d(!1)})})]})}function df(){return r.jsx(Ao,{client:lf,children:r.jsx(th,{children:r.jsx(cf,{})})})}Ki.createRoot(document.getElementById("root")).render(r.jsx(Oo.StrictMode,{children:r.jsx(df,{})}));export{Jh as A,se as B,bd as D,Ya as F,Dh as G,Is as M,Bh as O,$h as V,xt as _,bt as a,Fh as b,Uh as c,If as d,zf as e,gd as f,ri as g,de as h,Af as i,qh as j,Of as s,ci as u}; diff --git a/frontend/dist/assets/index-DaWuxWbx.css b/frontend/dist/assets/index-DaWuxWbx.css new file mode 100644 index 0000000000000000000000000000000000000000..6360fa8d6f6257126bc2a04821ccf2d725336b57 --- /dev/null +++ b/frontend/dist/assets/index-DaWuxWbx.css @@ -0,0 +1 @@ +*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:JetBrains Mono,Fira Code,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}*{box-sizing:border-box;scrollbar-width:thin;scrollbar-color:#1f2937 transparent}*::-webkit-scrollbar{width:6px;height:6px}*::-webkit-scrollbar-track{background:transparent}*::-webkit-scrollbar-thumb{background-color:#1f2937;border-radius:3px}*::-webkit-scrollbar-thumb:hover{background-color:#374151}html,body{margin:0;padding:0;background-color:#0a0e1a;color:#f9fafb;font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif;min-height:100vh;-webkit-tap-highlight-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;overscroll-behavior-y:none}button,a,input,select,textarea{touch-action:manipulation}#root{min-height:100vh;display:flex;flex-direction:column}.container{width:100%}@media (min-width: 480px){.container{max-width:480px}}@media (min-width: 640px){.container{max-width:640px}}@media (min-width: 768px){.container{max-width:768px}}@media (min-width: 1024px){.container{max-width:1024px}}@media (min-width: 1280px){.container{max-width:1280px}}@media (min-width: 1536px){.container{max-width:1536px}}.skeleton{background:linear-gradient(90deg,#1f2937,#374151,#1f2937);background-size:200% 100%;animation:shimmer 1.5s infinite linear;border-radius:4px}.glow-long{box-shadow:0 0 15px #10b98126}.glow-short{box-shadow:0 0 15px #ef444426}.signal-card-container{content-visibility:auto;contain-intrinsic-size:1px 310px;will-change:transform}.card{border-radius:.75rem;border-width:1px;--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1));--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.input-field{border-radius:.5rem;border-width:1px;--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1));--tw-bg-opacity: 1;background-color:rgb(26 35 50 / var(--tw-bg-opacity, 1));padding:.5rem .75rem;font-size:.875rem;line-height:1.25rem;--tw-text-opacity: 1;color:rgb(249 250 251 / var(--tw-text-opacity, 1))}.input-field::-moz-placeholder{--tw-placeholder-opacity: 1;color:rgb(75 85 99 / var(--tw-placeholder-opacity, 1))}.input-field::placeholder{--tw-placeholder-opacity: 1;color:rgb(75 85 99 / var(--tw-placeholder-opacity, 1))}.input-field{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.input-field:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1));outline:2px solid transparent;outline-offset:2px;--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000);--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.no-scrollbar::-webkit-scrollbar{display:none}.no-scrollbar{-ms-overflow-style:none;scrollbar-width:none}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:0}.inset-y-0{top:0;bottom:0}.-bottom-1{bottom:-.25rem}.-right-1{right:-.25rem}.-right-2{right:-.5rem}.-top-0\.5{top:-.125rem}.-top-1{top:-.25rem}.bottom-0{bottom:0}.bottom-4{bottom:1rem}.left-0{left:0}.left-1\/2{left:50%}.left-2\.5{left:.625rem}.left-3{left:.75rem}.right-0{right:0}.right-2{right:.5rem}.right-2\.5{right:.625rem}.right-3{right:.75rem}.right-4{right:1rem}.top-0{top:0}.top-1\/2{top:50%}.top-2{top:.5rem}.top-full{top:100%}.z-10{z-index:10}.z-20{z-index:20}.z-40{z-index:40}.z-50{z-index:50}.z-\[100\]{z-index:100}.col-span-2{grid-column:span 2 / span 2}.m-auto{margin:auto}.mx-0\.5{margin-left:.125rem;margin-right:.125rem}.mx-3{margin-left:.75rem;margin-right:.75rem}.mx-auto{margin-left:auto;margin-right:auto}.my-0\.5{margin-top:.125rem;margin-bottom:.125rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.my-auto{margin-top:auto;margin-bottom:auto}.mb-0\.5{margin-bottom:.125rem}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.ml-1{margin-left:.25rem}.ml-2{margin-left:.5rem}.ml-4{margin-left:1rem}.mr-1\.5{margin-right:.375rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-2\.5{margin-top:.625rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.line-clamp-1{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-3{height:.75rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[185px\]{height:185px}.h-\[2px\]{height:2px}.h-\[34px\]{height:34px}.h-\[35vh\]{height:35vh}.h-\[40vh\]{height:40vh}.h-\[45vh\]{height:45vh}.h-\[55vh\]{height:55vh}.h-\[calc\(100vh-3\.5rem\)\]{height:calc(100vh - 3.5rem)}.h-full{height:100%}.h-screen{height:100vh}.max-h-60{max-height:15rem}.max-h-80{max-height:20rem}.max-h-\[420px\]{max-height:420px}.max-h-\[80vh\]{max-height:80vh}.max-h-\[92vh\]{max-height:92vh}.min-h-\[160px\]{min-height:160px}.min-h-\[170px\]{min-height:170px}.min-h-\[400px\]{min-height:400px}.min-h-\[420px\]{min-height:420px}.min-h-\[44px\]{min-height:44px}.min-h-\[50vh\]{min-height:50vh}.w-1{width:.25rem}.w-1\.5{width:.375rem}.w-10{width:2.5rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-20{width:5rem}.w-24{width:6rem}.w-28{width:7rem}.w-32{width:8rem}.w-4{width:1rem}.w-4\/5{width:80%}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-72{width:18rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-full{width:100%}.w-px{width:1px}.min-w-0{min-width:0px}.max-w-2xl{max-width:42rem}.max-w-4xl{max-width:56rem}.max-w-6xl{max-width:72rem}.max-w-\[100px\]{max-width:100px}.max-w-\[130px\]{max-width:130px}.max-w-\[70px\]{max-width:70px}.max-w-\[85\%\]{max-width:85%}.max-w-\[95\%\]{max-width:95%}.max-w-full{max-width:100%}.max-w-md{max-width:28rem}.max-w-sm{max-width:24rem}.max-w-xl{max-width:36rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-0{--tw-translate-y: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-2{--tw-translate-y: .5rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes bounce{0%,to{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}.animate-bounce{animation:bounce 1s infinite}@keyframes fade-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fade-in .3s ease-out}@keyframes ping{75%,to{transform:scale(2);opacity:0}}.animate-ping{animation:ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes pulse-green{0%,to{box-shadow:0 0 #10b98166}50%{box-shadow:0 0 0 8px #10b98100}}.animate-pulse-green{animation:pulse-green 2s infinite}@keyframes pulse-red{0%,to{box-shadow:0 0 #ef444466}50%{box-shadow:0 0 0 8px #ef444400}}.animate-pulse-red{animation:pulse-red 2s infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize{resize:both}.list-disc{list-style-type:disc}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.items-baseline{align-items:baseline}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.justify-around{justify-content:space-around}.gap-0\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-2\.5{gap:.625rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-2\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.625rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.625rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-3\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.875rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.875rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-border>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(31 41 55 / var(--tw-divide-opacity, 1))}.self-end{align-self:flex-end}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-normal{white-space:normal}.whitespace-nowrap{white-space:nowrap}.break-words{overflow-wrap:break-word}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.rounded-b-xl{border-bottom-right-radius:.75rem;border-bottom-left-radius:.75rem}.rounded-l-full{border-top-left-radius:9999px;border-bottom-left-radius:9999px}.rounded-r-full{border-top-right-radius:9999px;border-bottom-right-radius:9999px}.rounded-tl-sm{border-top-left-radius:.125rem}.rounded-tr-sm{border-top-right-radius:.125rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-accent-blue{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-accent-blue\/20{border-color:#3b82f633}.border-accent-blue\/30{border-color:#3b82f64d}.border-accent-blue\/40{border-color:#3b82f666}.border-accent-yellow\/20{border-color:#f59e0b33}.border-accent-yellow\/30{border-color:#f59e0b4d}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-amber-500\/20{border-color:#f59e0b33}.border-amber-500\/25{border-color:#f59e0b40}.border-amber-500\/30{border-color:#f59e0b4d}.border-amber-500\/35{border-color:#f59e0b59}.border-amber-500\/40{border-color:#f59e0b66}.border-border{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.border-border\/30{border-color:#1f29374d}.border-border\/40{border-color:#1f293766}.border-border\/50{border-color:#1f293780}.border-border\/60{border-color:#1f293799}.border-border\/70{border-color:#1f2937b3}.border-border\/80{border-color:#1f2937cc}.border-border\/90{border-color:#1f2937e6}.border-current{border-color:currentColor}.border-cyan-500{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.border-cyan-500\/30{border-color:#06b6d44d}.border-cyan-500\/35{border-color:#06b6d459}.border-cyan-500\/40{border-color:#06b6d466}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-emerald-500\/20{border-color:#10b98133}.border-emerald-500\/25{border-color:#10b98140}.border-emerald-500\/30{border-color:#10b9814d}.border-emerald-500\/40{border-color:#10b98166}.border-gray-400{--tw-border-opacity: 1;border-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.border-gray-500\/30{border-color:#6b72804d}.border-indigo-500\/35{border-color:#6366f159}.border-orange-500{--tw-border-opacity: 1;border-color:rgb(249 115 22 / var(--tw-border-opacity, 1))}.border-purple-500{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.border-purple-500\/20{border-color:#a855f733}.border-purple-500\/25{border-color:#a855f740}.border-purple-500\/30{border-color:#a855f74d}.border-purple-500\/40{border-color:#a855f766}.border-purple-500\/50{border-color:#a855f780}.border-red-500\/20{border-color:#ef444433}.border-red-500\/30{border-color:#ef44444d}.border-red-500\/40{border-color:#ef444466}.border-rose-500{--tw-border-opacity: 1;border-color:rgb(244 63 94 / var(--tw-border-opacity, 1))}.border-rose-500\/20{border-color:#f43f5e33}.border-rose-500\/25{border-color:#f43f5e40}.border-rose-500\/30{border-color:#f43f5e4d}.border-rose-500\/40{border-color:#f43f5e66}.border-signal-long{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-signal-long\/20{border-color:#10b98133}.border-signal-long\/30{border-color:#10b9814d}.border-signal-long\/40{border-color:#10b98166}.border-signal-short\/20{border-color:#ef444433}.border-signal-short\/30{border-color:#ef44444d}.border-signal-short\/40{border-color:#ef444466}.border-sky-500\/20{border-color:#0ea5e933}.border-sky-500\/40{border-color:#0ea5e966}.border-transparent{border-color:transparent}.border-t-purple-500{--tw-border-opacity: 1;border-top-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.border-t-transparent{border-top-color:transparent}.bg-\[\#090b0e\]{--tw-bg-opacity: 1;background-color:rgb(9 11 14 / var(--tw-bg-opacity, 1))}.bg-\[\#090b0e\]\/80{background-color:#090b0ecc}.bg-\[\#090b0e\]\/90{background-color:#090b0ee6}.bg-accent-blue{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-accent-blue\/10{background-color:#3b82f61a}.bg-accent-blue\/15{background-color:#3b82f626}.bg-accent-blue\/20{background-color:#3b82f633}.bg-accent-yellow{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-amber-400{--tw-bg-opacity: 1;background-color:rgb(251 191 36 / var(--tw-bg-opacity, 1))}.bg-amber-500\/10{background-color:#f59e0b1a}.bg-amber-500\/15{background-color:#f59e0b26}.bg-amber-500\/20{background-color:#f59e0b33}.bg-amber-600{--tw-bg-opacity: 1;background-color:rgb(217 119 6 / var(--tw-bg-opacity, 1))}.bg-amber-950\/15{background-color:#451a0326}.bg-amber-950\/20{background-color:#451a0333}.bg-bg-card{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-bg-card\/50{background-color:#11182780}.bg-bg-card\/70{background-color:#111827b3}.bg-bg-card\/80{background-color:#111827cc}.bg-bg-card\/90{background-color:#111827e6}.bg-bg-card\/95{background-color:#111827f2}.bg-bg-elevated{--tw-bg-opacity: 1;background-color:rgb(26 35 50 / var(--tw-bg-opacity, 1))}.bg-bg-elevated\/20{background-color:#1a233233}.bg-bg-elevated\/30{background-color:#1a23324d}.bg-bg-elevated\/40{background-color:#1a233266}.bg-bg-elevated\/50{background-color:#1a233280}.bg-bg-elevated\/60{background-color:#1a233299}.bg-bg-elevated\/70{background-color:#1a2332b3}.bg-bg-elevated\/80{background-color:#1a2332cc}.bg-bg-elevated\/90{background-color:#1a2332e6}.bg-bg-primary{--tw-bg-opacity: 1;background-color:rgb(10 14 26 / var(--tw-bg-opacity, 1))}.bg-bg-primary\/50{background-color:#0a0e1a80}.bg-bg-primary\/60{background-color:#0a0e1a99}.bg-bg-primary\/80{background-color:#0a0e1acc}.bg-bg-primary\/90{background-color:#0a0e1ae6}.bg-black\/80{background-color:#000c}.bg-blue-500\/10{background-color:#3b82f61a}.bg-cyan-400{--tw-bg-opacity: 1;background-color:rgb(34 211 238 / var(--tw-bg-opacity, 1))}.bg-cyan-500\/15{background-color:#06b6d426}.bg-cyan-500\/20{background-color:#06b6d433}.bg-cyan-950\/15{background-color:#08334426}.bg-emerald-400{--tw-bg-opacity: 1;background-color:rgb(52 211 153 / var(--tw-bg-opacity, 1))}.bg-emerald-500{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.bg-emerald-500\/10{background-color:#10b9811a}.bg-emerald-500\/15{background-color:#10b98126}.bg-emerald-500\/20{background-color:#10b98133}.bg-emerald-500\/30{background-color:#10b9814d}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.bg-emerald-950\/15{background-color:#022c2226}.bg-gray-500{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.bg-gray-500\/10{background-color:#6b72801a}.bg-gray-500\/15{background-color:#6b728026}.bg-gray-500\/20{background-color:#6b728033}.bg-gray-500\/30{background-color:#6b72804d}.bg-indigo-500\/15{background-color:#6366f126}.bg-orange-500\/20{background-color:#f9731633}.bg-purple-400{--tw-bg-opacity: 1;background-color:rgb(192 132 252 / var(--tw-bg-opacity, 1))}.bg-purple-500\/10{background-color:#a855f71a}.bg-purple-500\/15{background-color:#a855f726}.bg-purple-500\/20{background-color:#a855f733}.bg-purple-500\/25{background-color:#a855f740}.bg-purple-500\/30{background-color:#a855f74d}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-purple-600\/15{background-color:#9333ea26}.bg-purple-600\/20{background-color:#9333ea33}.bg-purple-600\/30{background-color:#9333ea4d}.bg-purple-950\/15{background-color:#3b076426}.bg-purple-950\/20{background-color:#3b076433}.bg-purple-950\/30{background-color:#3b07644d}.bg-red-500\/10{background-color:#ef44441a}.bg-red-500\/20{background-color:#ef444433}.bg-red-950\/40{background-color:#450a0a66}.bg-rose-400{--tw-bg-opacity: 1;background-color:rgb(251 113 133 / var(--tw-bg-opacity, 1))}.bg-rose-500{--tw-bg-opacity: 1;background-color:rgb(244 63 94 / var(--tw-bg-opacity, 1))}.bg-rose-500\/10{background-color:#f43f5e1a}.bg-rose-500\/15{background-color:#f43f5e26}.bg-rose-500\/20{background-color:#f43f5e33}.bg-rose-500\/30{background-color:#f43f5e4d}.bg-rose-600{--tw-bg-opacity: 1;background-color:rgb(225 29 72 / var(--tw-bg-opacity, 1))}.bg-rose-950\/15{background-color:#4c051926}.bg-rose-950\/60{background-color:#4c051999}.bg-signal-long{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.bg-signal-long-bg,.bg-signal-long\/10{background-color:#10b9811a}.bg-signal-long\/15{background-color:#10b98126}.bg-signal-long\/20{background-color:#10b98133}.bg-signal-neutral-bg{background-color:#6b72801a}.bg-signal-short{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-signal-short-bg,.bg-signal-short\/10{background-color:#ef44441a}.bg-signal-short\/15{background-color:#ef444426}.bg-signal-short\/20{background-color:#ef444433}.bg-sky-400{--tw-bg-opacity: 1;background-color:rgb(56 189 248 / var(--tw-bg-opacity, 1))}.bg-sky-500\/10{background-color:#0ea5e91a}.bg-sky-500\/15{background-color:#0ea5e926}.bg-sky-600{--tw-bg-opacity: 1;background-color:rgb(2 132 199 / var(--tw-bg-opacity, 1))}.bg-text-muted{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.bg-text-muted\/30{background-color:#4b55634d}.bg-text-muted\/40{background-color:#4b556366}.bg-transparent{background-color:transparent}.bg-yellow-500\/10{background-color:#eab3081a}.bg-gradient-to-b{background-image:linear-gradient(to bottom,var(--tw-gradient-stops))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-amber-500{--tw-gradient-from: #f59e0b var(--tw-gradient-from-position);--tw-gradient-to: rgb(245 158 11 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-amber-950\/20{--tw-gradient-from: rgb(69 26 3 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(69 26 3 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-cyan-950\/20{--tw-gradient-from: rgb(8 51 68 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(8 51 68 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-emerald-500{--tw-gradient-from: #10b981 var(--tw-gradient-from-position);--tw-gradient-to: rgb(16 185 129 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-emerald-950\/25{--tw-gradient-from: rgb(2 44 34 / .25) var(--tw-gradient-from-position);--tw-gradient-to: rgb(2 44 34 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-500{--tw-gradient-from: #6b7280 var(--tw-gradient-from-position);--tw-gradient-to: rgb(107 114 128 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-orange-500{--tw-gradient-from: #f97316 var(--tw-gradient-from-position);--tw-gradient-to: rgb(249 115 22 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-500\/20{--tw-gradient-from: rgb(168 85 247 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-600{--tw-gradient-from: #9333ea var(--tw-gradient-from-position);--tw-gradient-to: rgb(147 51 234 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-950\/40{--tw-gradient-from: rgb(59 7 100 / .4) var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 7 100 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-500{--tw-gradient-from: #ef4444 var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 68 68 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-rose-950\/20{--tw-gradient-from: rgb(76 5 25 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(76 5 25 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-rose-950\/25{--tw-gradient-from: rgb(76 5 25 / .25) var(--tw-gradient-from-position);--tw-gradient-to: rgb(76 5 25 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-signal-long\/10{--tw-gradient-from: rgb(16 185 129 / .1) var(--tw-gradient-from-position);--tw-gradient-to: rgb(16 185 129 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-signal-short\/10{--tw-gradient-from: rgb(239 68 68 / .1) var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 68 68 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-transparent{--tw-gradient-from: transparent var(--tw-gradient-from-position);--tw-gradient-to: rgb(0 0 0 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-yellow-500{--tw-gradient-from: #eab308 var(--tw-gradient-from-position);--tw-gradient-to: rgb(234 179 8 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-bg-card{--tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #111827 var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-bg-elevated\/40{--tw-gradient-to: rgb(26 35 50 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(26 35 50 / .4) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-purple-500{--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #a855f7 var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-amber-400{--tw-gradient-to: #fbbf24 var(--tw-gradient-to-position)}.to-amber-600{--tw-gradient-to: #d97706 var(--tw-gradient-to-position)}.to-bg-card{--tw-gradient-to: #111827 var(--tw-gradient-to-position)}.to-blue-500\/20{--tw-gradient-to: rgb(59 130 246 / .2) var(--tw-gradient-to-position)}.to-gray-400{--tw-gradient-to: #9ca3af var(--tw-gradient-to-position)}.to-green-400{--tw-gradient-to: #4ade80 var(--tw-gradient-to-position)}.to-indigo-600{--tw-gradient-to: #4f46e5 var(--tw-gradient-to-position)}.to-purple-950\/20{--tw-gradient-to: rgb(59 7 100 / .2) var(--tw-gradient-to-position)}.to-rose-400{--tw-gradient-to: #fb7185 var(--tw-gradient-to-position)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.fill-black{fill:#000}.fill-yellow-300{fill:#fde047}.p-0\.5{padding:.125rem}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-3{padding:.75rem}.p-3\.5{padding:.875rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.px-0{padding-left:0;padding-right:0}.px-0\.5{padding-left:.125rem;padding-right:.125rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-3\.5{padding-left:.875rem;padding-right:.875rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-3\.5{padding-top:.875rem;padding-bottom:.875rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-1{padding-bottom:.25rem}.pb-1\.5{padding-bottom:.375rem}.pb-16{padding-bottom:4rem}.pb-2{padding-bottom:.5rem}.pb-2\.5{padding-bottom:.625rem}.pb-20{padding-bottom:5rem}.pb-3{padding-bottom:.75rem}.pb-\[max\(0\.35rem\,env\(safe-area-inset-bottom\)\)\]{padding-bottom:max(.35rem,env(safe-area-inset-bottom))}.pl-3{padding-left:.75rem}.pl-4{padding-left:1rem}.pl-7{padding-left:1.75rem}.pl-8{padding-left:2rem}.pl-9{padding-left:2.25rem}.pr-1{padding-right:.25rem}.pr-10{padding-right:2.5rem}.pr-16{padding-right:4rem}.pr-2{padding-right:.5rem}.pr-2\.5{padding-right:.625rem}.pr-3{padding-right:.75rem}.pr-8{padding-right:2rem}.pr-9{padding-right:2.25rem}.pt-0\.5{padding-top:.125rem}.pt-1{padding-top:.25rem}.pt-2{padding-top:.5rem}.pt-2\.5{padding-top:.625rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.align-bottom{vertical-align:bottom}.font-mono{font-family:JetBrains Mono,Fira Code,monospace}.font-sans{font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"}.text-\[10\.5px\]{font-size:10.5px}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[8px\]{font-size:8px}.text-\[9px\]{font-size:9px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.capitalize{text-transform:capitalize}.italic{font-style:italic}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.leading-snug{line-height:1.375}.leading-tight{line-height:1.25}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-accent-blue{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-accent-blue\/80{color:#3b82f6cc}.text-accent-blue\/90{color:#3b82f6e6}.text-accent-yellow{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity, 1))}.text-amber-100\/90{color:#fef3c7e6}.text-amber-200{--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity, 1))}.text-amber-200\/80{color:#fde68acc}.text-amber-300{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.text-amber-300\/80{color:#fcd34dcc}.text-amber-300\/90{color:#fcd34de6}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-amber-400\/90{color:#fbbf24e6}.text-bg-primary{--tw-text-opacity: 1;color:rgb(10 14 26 / var(--tw-text-opacity, 1))}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.text-border{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-cyan-300{--tw-text-opacity: 1;color:rgb(103 232 249 / var(--tw-text-opacity, 1))}.text-cyan-400{--tw-text-opacity: 1;color:rgb(34 211 238 / var(--tw-text-opacity, 1))}.text-emerald-200{--tw-text-opacity: 1;color:rgb(167 243 208 / var(--tw-text-opacity, 1))}.text-emerald-300{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.text-emerald-300\/70{color:#6ee7b7b3}.text-emerald-300\/80{color:#6ee7b7cc}.text-emerald-300\/90{color:#6ee7b7e6}.text-emerald-400{--tw-text-opacity: 1;color:rgb(52 211 153 / var(--tw-text-opacity, 1))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-indigo-300{--tw-text-opacity: 1;color:rgb(165 180 252 / var(--tw-text-opacity, 1))}.text-orange-300{--tw-text-opacity: 1;color:rgb(253 186 116 / var(--tw-text-opacity, 1))}.text-orange-400{--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.text-purple-100{--tw-text-opacity: 1;color:rgb(243 232 255 / var(--tw-text-opacity, 1))}.text-purple-200{--tw-text-opacity: 1;color:rgb(233 213 255 / var(--tw-text-opacity, 1))}.text-purple-200\/80{color:#e9d5ffcc}.text-purple-200\/90{color:#e9d5ffe6}.text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.text-purple-300\/80{color:#d8b4fecc}.text-purple-300\/90{color:#d8b4fee6}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-red-100{--tw-text-opacity: 1;color:rgb(254 226 226 / var(--tw-text-opacity, 1))}.text-red-200{--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.text-red-200\/90{color:#fecacae6}.text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-400\/80{color:#f87171cc}.text-rose-100{--tw-text-opacity: 1;color:rgb(255 228 230 / var(--tw-text-opacity, 1))}.text-rose-200{--tw-text-opacity: 1;color:rgb(254 205 211 / var(--tw-text-opacity, 1))}.text-rose-200\/80{color:#fecdd3cc}.text-rose-200\/90{color:#fecdd3e6}.text-rose-300{--tw-text-opacity: 1;color:rgb(253 164 175 / var(--tw-text-opacity, 1))}.text-rose-300\/70{color:#fda4afb3}.text-rose-300\/80{color:#fda4afcc}.text-rose-400{--tw-text-opacity: 1;color:rgb(251 113 133 / var(--tw-text-opacity, 1))}.text-signal-long{--tw-text-opacity: 1;color:rgb(16 185 129 / var(--tw-text-opacity, 1))}.text-signal-long\/80{color:#10b981cc}.text-signal-long\/90{color:#10b981e6}.text-signal-short{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-sky-300{--tw-text-opacity: 1;color:rgb(125 211 252 / var(--tw-text-opacity, 1))}.text-sky-400{--tw-text-opacity: 1;color:rgb(56 189 248 / var(--tw-text-opacity, 1))}.text-text-muted{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-text-muted\/40{color:#4b556366}.text-text-muted\/70{color:#4b5563b3}.text-text-primary{--tw-text-opacity: 1;color:rgb(249 250 251 / var(--tw-text-opacity, 1))}.text-text-primary\/95{color:#f9fafbf2}.text-text-secondary{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-text-secondary\/70{color:#6b7280b3}.text-text-secondary\/80{color:#6b7280cc}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-300{--tw-text-opacity: 1;color:rgb(253 224 71 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.underline{text-decoration-line:underline}.accent-emerald-500{accent-color:#10b981}.accent-purple-500{accent-color:#a855f7}.opacity-0{opacity:0}.opacity-100{opacity:1}.opacity-50{opacity:.5}.opacity-70{opacity:.7}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_25px_rgba\(16\,185\,129\,0\.12\)\]{--tw-shadow: 0 0 25px rgba(16,185,129,.12);--tw-shadow-colored: 0 0 25px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_25px_rgba\(239\,68\,68\,0\.12\)\]{--tw-shadow: 0 0 25px rgba(239,68,68,.12);--tw-shadow-colored: 0 0 25px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 rgb(0 0 0 / .05);--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-accent-blue\/30{--tw-shadow-color: rgb(59 130 246 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-amber-400\/50{--tw-shadow-color: rgb(251 191 36 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-amber-500\/20{--tw-shadow-color: rgb(245 158 11 / .2);--tw-shadow: var(--tw-shadow-colored)}.shadow-amber-950\/30{--tw-shadow-color: rgb(69 26 3 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-cyan-400\/50{--tw-shadow-color: rgb(34 211 238 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-cyan-950\/30{--tw-shadow-color: rgb(8 51 68 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-emerald-400\/50{--tw-shadow-color: rgb(52 211 153 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-emerald-600\/30{--tw-shadow-color: rgb(5 150 105 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-emerald-950\/30{--tw-shadow-color: rgb(2 44 34 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-emerald-950\/40{--tw-shadow-color: rgb(2 44 34 / .4);--tw-shadow: var(--tw-shadow-colored)}.shadow-purple-500\/10{--tw-shadow-color: rgb(168 85 247 / .1);--tw-shadow: var(--tw-shadow-colored)}.shadow-purple-500\/20{--tw-shadow-color: rgb(168 85 247 / .2);--tw-shadow: var(--tw-shadow-colored)}.shadow-purple-500\/25{--tw-shadow-color: rgb(168 85 247 / .25);--tw-shadow: var(--tw-shadow-colored)}.shadow-purple-600\/10{--tw-shadow-color: rgb(147 51 234 / .1);--tw-shadow: var(--tw-shadow-colored)}.shadow-purple-600\/25{--tw-shadow-color: rgb(147 51 234 / .25);--tw-shadow: var(--tw-shadow-colored)}.shadow-purple-600\/30{--tw-shadow-color: rgb(147 51 234 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-rose-400\/50{--tw-shadow-color: rgb(251 113 133 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-rose-950\/30{--tw-shadow-color: rgb(76 5 25 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-rose-950\/40{--tw-shadow-color: rgb(76 5 25 / .4);--tw-shadow: var(--tw-shadow-colored)}.shadow-signal-long\/50{--tw-shadow-color: rgb(16 185 129 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-signal-short\/50{--tw-shadow-color: rgb(239 68 68 / .5);--tw-shadow: var(--tw-shadow-colored)}.shadow-sky-600\/30{--tw-shadow-color: rgb(2 132 199 / .3);--tw-shadow: var(--tw-shadow-colored)}.outline-none{outline:2px solid transparent;outline-offset:2px}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-accent-blue{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.ring-accent-blue\/50{--tw-ring-color: rgb(59 130 246 / .5)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur{--tw-backdrop-blur: blur(8px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-xl{--tw-backdrop-blur: blur(24px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-150{transition-duration:.15s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.duration-700{transition-duration:.7s}.ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}.marker\:text-accent-blue *::marker{color:#3b82f6}.marker\:text-accent-blue::marker{color:#3b82f6}.placeholder\:text-text-muted::-moz-placeholder{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.placeholder\:text-text-muted::placeholder{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:border-accent-blue:hover{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.hover\:border-accent-blue\/40:hover{border-color:#3b82f666}.hover\:border-accent-blue\/50:hover{border-color:#3b82f680}.hover\:border-amber-500\/50:hover{border-color:#f59e0b80}.hover\:border-border:hover{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.hover\:border-border\/80:hover{border-color:#1f2937cc}.hover\:border-cyan-500\/60:hover{border-color:#06b6d499}.hover\:border-emerald-500\/50:hover{border-color:#10b98180}.hover\:border-emerald-500\/60:hover{border-color:#10b98199}.hover\:border-purple-400:hover{--tw-border-opacity: 1;border-color:rgb(192 132 252 / var(--tw-border-opacity, 1))}.hover\:border-purple-500\/40:hover{border-color:#a855f766}.hover\:border-purple-500\/50:hover{border-color:#a855f780}.hover\:border-rose-500\/60:hover{border-color:#f43f5e99}.hover\:border-signal-long\/60:hover{border-color:#10b98199}.hover\:border-signal-short\/60:hover{border-color:#ef444499}.hover\:border-sky-400:hover{--tw-border-opacity: 1;border-color:rgb(56 189 248 / var(--tw-border-opacity, 1))}.hover\:border-text-secondary:hover{--tw-border-opacity: 1;border-color:rgb(107 114 128 / var(--tw-border-opacity, 1))}.hover\:bg-accent-blue\/20:hover{background-color:#3b82f633}.hover\:bg-accent-blue\/90:hover{background-color:#3b82f6e6}.hover\:bg-amber-500:hover{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.hover\:bg-amber-500\/20:hover{background-color:#f59e0b33}.hover\:bg-amber-500\/25:hover{background-color:#f59e0b40}.hover\:bg-bg-card:hover{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.hover\:bg-bg-elevated:hover{--tw-bg-opacity: 1;background-color:rgb(26 35 50 / var(--tw-bg-opacity, 1))}.hover\:bg-bg-elevated\/70:hover{background-color:#1a2332b3}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-border:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-500:hover{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-500\/20:hover{background-color:#10b98133}.hover\:bg-gray-500\/20:hover{background-color:#6b728033}.hover\:bg-purple-500:hover{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.hover\:bg-purple-500\/20:hover{background-color:#a855f733}.hover\:bg-purple-600\/20:hover{background-color:#9333ea33}.hover\:bg-purple-600\/30:hover{background-color:#9333ea4d}.hover\:bg-purple-600\/50:hover{background-color:#9333ea80}.hover\:bg-purple-950\/40:hover{background-color:#3b076466}.hover\:bg-red-500\/20:hover{background-color:#ef444433}.hover\:bg-red-500\/30:hover{background-color:#ef44444d}.hover\:bg-rose-500:hover{--tw-bg-opacity: 1;background-color:rgb(244 63 94 / var(--tw-bg-opacity, 1))}.hover\:bg-rose-500\/20:hover{background-color:#f43f5e33}.hover\:bg-signal-long-bg:hover{background-color:#10b9811a}.hover\:bg-signal-short-bg:hover{background-color:#ef44441a}.hover\:bg-sky-500\/25:hover{background-color:#0ea5e940}.hover\:from-amber-400:hover{--tw-gradient-from: #fbbf24 var(--tw-gradient-from-position);--tw-gradient-to: rgb(251 191 36 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:from-purple-500:hover{--tw-gradient-from: #a855f7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:from-purple-500\/30:hover{--tw-gradient-from: rgb(168 85 247 / .3) var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:to-amber-500:hover{--tw-gradient-to: #f59e0b var(--tw-gradient-to-position)}.hover\:to-blue-500\/30:hover{--tw-gradient-to: rgb(59 130 246 / .3) var(--tw-gradient-to-position)}.hover\:to-indigo-500:hover{--tw-gradient-to: #6366f1 var(--tw-gradient-to-position)}.hover\:text-amber-300:hover{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.hover\:text-amber-400:hover{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.hover\:text-emerald-300:hover{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.hover\:text-emerald-400:hover{--tw-text-opacity: 1;color:rgb(52 211 153 / var(--tw-text-opacity, 1))}.hover\:text-purple-200:hover{--tw-text-opacity: 1;color:rgb(233 213 255 / var(--tw-text-opacity, 1))}.hover\:text-purple-300:hover{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.hover\:text-red-300:hover{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.hover\:text-rose-200:hover{--tw-text-opacity: 1;color:rgb(254 205 211 / var(--tw-text-opacity, 1))}.hover\:text-rose-400:hover{--tw-text-opacity: 1;color:rgb(251 113 133 / var(--tw-text-opacity, 1))}.hover\:text-signal-long:hover{--tw-text-opacity: 1;color:rgb(16 185 129 / var(--tw-text-opacity, 1))}.hover\:text-signal-short:hover{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.hover\:text-sky-300:hover{--tw-text-opacity: 1;color:rgb(125 211 252 / var(--tw-text-opacity, 1))}.hover\:text-text-primary:hover{--tw-text-opacity: 1;color:rgb(249 250 251 / var(--tw-text-opacity, 1))}.hover\:text-text-secondary:hover{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-90:hover{opacity:.9}.focus\:border-accent-blue:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\:border-amber-400:focus{--tw-border-opacity: 1;border-color:rgb(251 191 36 / var(--tw-border-opacity, 1))}.focus\:border-emerald-400:focus{--tw-border-opacity: 1;border-color:rgb(52 211 153 / var(--tw-border-opacity, 1))}.focus\:border-purple-400:focus{--tw-border-opacity: 1;border-color:rgb(192 132 252 / var(--tw-border-opacity, 1))}.focus\:border-purple-500:focus{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.focus\:border-purple-500\/50:focus{border-color:#a855f780}.focus\:border-purple-500\/60:focus{border-color:#a855f799}.focus\:border-rose-400:focus{--tw-border-opacity: 1;border-color:rgb(251 113 133 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-accent-blue:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.focus\:ring-amber-400:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(251 191 36 / var(--tw-ring-opacity, 1))}.active\:scale-90:active{--tw-scale-x: .9;--tw-scale-y: .9;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.active\:scale-95:active{--tw-scale-x: .95;--tw-scale-y: .95;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.group:hover .group-hover\:scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}@media (min-width: 480px){.xs\:inline{display:inline}.xs\:hidden{display:none}.xs\:max-w-\[100px\]{max-width:100px}.xs\:max-w-\[170px\]{max-width:170px}.xs\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width: 640px){.sm\:left-auto{left:auto}.sm\:col-span-1{grid-column:span 1 / span 1}.sm\:col-span-3{grid-column:span 3 / span 3}.sm\:mx-5{margin-left:1.25rem;margin-right:1.25rem}.sm\:mb-5{margin-bottom:1.25rem}.sm\:mb-6{margin-bottom:1.5rem}.sm\:inline{display:inline}.sm\:flex{display:flex}.sm\:hidden{display:none}.sm\:w-32{width:8rem}.sm\:w-60{width:15rem}.sm\:w-80{width:20rem}.sm\:w-auto{width:auto}.sm\:max-w-\[120px\]{max-width:120px}.sm\:max-w-\[220px\]{max-width:220px}.sm\:max-w-\[75\%\]{max-width:75%}.sm\:max-w-\[90\%\]{max-width:90%}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-2{gap:.5rem}.sm\:gap-2\.5{gap:.625rem}.sm\:gap-3{gap:.75rem}.sm\:gap-4{gap:1rem}.sm\:self-auto{align-self:auto}.sm\:border-r{border-right-width:1px}.sm\:border-border{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.sm\:bg-transparent{background-color:transparent}.sm\:p-0{padding:0}.sm\:p-3{padding:.75rem}.sm\:p-3\.5{padding:.875rem}.sm\:p-4{padding:1rem}.sm\:p-5{padding:1.25rem}.sm\:p-6{padding:1.5rem}.sm\:px-2{padding-left:.5rem;padding-right:.5rem}.sm\:px-3{padding-left:.75rem;padding-right:.75rem}.sm\:px-3\.5{padding-left:.875rem;padding-right:.875rem}.sm\:px-5{padding-left:1.25rem;padding-right:1.25rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.sm\:py-4{padding-top:1rem;padding-bottom:1rem}.sm\:py-5{padding-top:1.25rem;padding-bottom:1.25rem}.sm\:text-left{text-align:left}.sm\:text-2xl{font-size:1.5rem;line-height:2rem}.sm\:text-\[10px\]{font-size:10px}.sm\:text-\[11px\]{font-size:11px}.sm\:text-\[12px\]{font-size:12px}.sm\:text-\[13px\]{font-size:13px}.sm\:text-\[9px\]{font-size:9px}.sm\:text-base{font-size:1rem;line-height:1.5rem}.sm\:text-lg{font-size:1.125rem;line-height:1.75rem}.sm\:text-sm{font-size:.875rem;line-height:1.25rem}.sm\:text-xs{font-size:.75rem;line-height:1rem}.sm\:opacity-0{opacity:0}.group:hover .sm\:group-hover\:opacity-100{opacity:1}}@media (min-width: 768px){.md\:inline{display:inline}.md\:flex{display:flex}.md\:hidden{display:none}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:pb-4{padding-bottom:1rem}.md\:pb-5{padding-bottom:1.25rem}}@media (min-width: 1024px){.lg\:inline{display:inline}.lg\:flex{display:flex}.lg\:w-72{width:18rem}.lg\:w-80{width:20rem}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:flex-row{flex-direction:row}.lg\:items-center{align-items:center}.lg\:border-l{border-left-width:1px}.lg\:border-t-0{border-top-width:0px}}@media (min-width: 1280px){.xl\:w-80{width:20rem}.xl\:w-96{width:24rem}.xl\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}} diff --git a/frontend/dist/assets/index-FYyQL2Qc.js b/frontend/dist/assets/index-FYyQL2Qc.js deleted file mode 100644 index 577deaf597cae60b80bbd4cf752c18340726bc52..0000000000000000000000000000000000000000 --- a/frontend/dist/assets/index-FYyQL2Qc.js +++ /dev/null @@ -1,45 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AddPairModal-D8YkLLF_.js","assets/vendor-query-BSPl6-aq.js","assets/vendor-icons-BBZkXbgm.js","assets/vendor-react-BnvheTds.js","assets/AIAnalysisPanel-BbXTq8TV.js","assets/GlobalAISettingsModal-y_W5Q-P7.js","assets/ServerSettingsModal-BJC6WDDG.js"])))=>i.map(i=>d[i]); -import{j as r,u as as,a as os,b as Zt,r as y,Q as To,c as Ro,R as Po}from"./vendor-query-BSPl6-aq.js";import{r as Lo}from"./vendor-react-BnvheTds.js";import{M as ta,T as Mt,a as Qe,X as Ct,I as Ao,C as ar,b as sa,B as ia,P as or,L as Xs,S as Zs,c as Ye,d as ve,e as Et,Z as Ae,f as rt,g as es,h as Fs,i as nt,j as Fe,R as Re,k as Us,l as jt,m as Be,n as Oo,F as ts,A as zo,o as ra,p as na,q as Io,K as $o,r as Do,s as Qt,W as Bo,t as Tt,u as Fo,v as Uo,w as lr,x as qo,y as Wo,z as Ho,D as yt,E as cr,G as ei,H as Vo,J as Rr,N as Ko,O as Go,Q as Qo,U as Yo,V as Jo,Y as Xo,_ as Zo,$ as aa,a0 as el}from"./vendor-icons-BBZkXbgm.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))i(n);new MutationObserver(n=>{for(const a of n)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(n){const a={};return n.integrity&&(a.integrity=n.integrity),n.referrerPolicy&&(a.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?a.credentials="include":n.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(n){if(n.ep)return;n.ep=!0;const a=t(n);fetch(n.href,a)}})();var Hi={},Pr=Lo;Hi.createRoot=Pr.createRoot,Hi.hydrateRoot=Pr.hydrateRoot;const tl="modulepreload",sl=function(s){return"/"+s},Lr={},pt=function(e,t,i){let n=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");n=Promise.allSettled(t.map(c=>{if(c=sl(c),c in Lr)return;Lr[c]=!0;const d=c.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${h}`))return;const u=document.createElement("link");if(u.rel=d?"stylesheet":tl,d||(u.as="script"),u.crossOrigin="",u.href=c,l&&u.setAttribute("nonce",l),document.head.appendChild(u),d)return new Promise((m,x)=>{u.addEventListener("load",m),u.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${c}`)))})}))}function a(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return n.then(o=>{for(const l of o||[])l.status==="rejected"&&a(l.reason);return e().catch(a)})},il={LONG:{label:"LONG",icon:r.jsx(Qe,{size:14,strokeWidth:2.5}),classes:"bg-signal-long-bg text-signal-long border border-signal-long/40"},SHORT:{label:"SHORT",icon:r.jsx(Mt,{size:14,strokeWidth:2.5}),classes:"bg-signal-short-bg text-signal-short border border-signal-short/40"},NEUTRAL:{label:"NEUTRAL",icon:r.jsx(ta,{size:14,strokeWidth:2.5}),classes:"bg-signal-neutral-bg text-text-secondary border border-border"}},rl={sm:"text-xs px-2 py-0.5 gap-1",md:"text-sm px-2.5 py-1 gap-1.5",lg:"text-base px-3 py-1.5 gap-2"};function dr({direction:s,size:e="md"}){const{label:t,icon:i,classes:n}=il[s];return r.jsxs("span",{className:`inline-flex items-center font-mono font-bold rounded-md ${n} ${rl[e]}`,children:[i,t]})}function oa(s,e){return function(){return s.apply(e,arguments)}}const{toString:nl}=Object.prototype,{getPrototypeOf:Je}=Object,{iterator:ls,toStringTag:la}=Symbol,ss=(({hasOwnProperty:s})=>(e,t)=>s.call(e,t))(Object.prototype),ca=s=>typeof s=="string"&&(s==="__proto__"||s==="constructor"||s==="prototype"),da=(s,e,t)=>s===Object.prototype||!t&&e===null,al=s=>{if(!Object.isExtensible(s))return!1;const e=Object.getOwnPropertyNames(s);return Object.getOwnPropertySymbols&&e.push(...Object.getOwnPropertySymbols(s)),e.every(t=>{if(ca(t))return!1;const i=Object.getOwnPropertyDescriptor(s,t);return!!i&&i.configurable&&i.writable===!0})},is=(s,e)=>{let t=s;const i=[];for(;t!=null;){if(i.indexOf(t)!==-1)return!1;i.push(t);const n=Je(t);if(da(t,n,t===s))return!1;if(ss(t,e))return!0;t=n}return!1},ol=(s,e)=>s!=null&&is(s,e)?s[e]:void 0,ll=s=>{if(s==null||typeof s!="object"&&typeof s!="function")return s;const e=Je(s);if(e===null&&al(s))return s;const t=Object.create(null),i=Object.create(null),n=[];let a=s;for(;a!=null&&n.indexOf(a)===-1;){n.push(a);const o=a===s?e:Je(a);if(da(a,o,a===s))break;const l=Object.getOwnPropertyNames(a);Object.getOwnPropertySymbols&&l.push(...Object.getOwnPropertySymbols(a));for(const c of l)ca(c)||ss(i,c)||(t[c]=s[c],i[c]=!0);a=o}return t},hr=(s=>e=>{const t=nl.call(e);return s[t]||(s[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),Ee=s=>(s=s.toLowerCase(),e=>hr(e)===s),ti=s=>e=>typeof e===s,{isArray:at}=Array,ot=ti("undefined");function Ot(s){return s!==null&&!ot(s)&&s.constructor!==null&&!ot(s.constructor)&&je(s.constructor.isBuffer)&&s.constructor.isBuffer(s)}const ha=Ee("ArrayBuffer");function cl(s){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(s):e=s&&s.buffer&&ha(s.buffer),e}const dl=ti("string"),je=ti("function"),ua=ti("number"),zt=s=>s!==null&&typeof s=="object",hl=s=>s===!0||s===!1,Ls=s=>{if(!zt(s))return!1;const e=Je(s);return(e===null||e===Object.prototype||Je(e)===null)&&!is(s,la)&&!is(s,ls)},ul=s=>{if(!zt(s)||Ot(s))return!1;try{return Object.keys(s).length===0&&Object.getPrototypeOf(s)===Object.prototype}catch{return!1}},ml=Ee("Date"),pl=Ee("File"),fl=s=>!!(s&&typeof s.uri<"u"),xl=s=>s&&typeof s.getParts<"u",bl=Ee("Blob"),gl=Ee("FileList"),vl=Ee("Set"),yl=s=>zt(s)&&je(s.pipe);function wl(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const Ar=wl(),Or=typeof Ar.FormData<"u"?Ar.FormData:void 0,Nl=s=>{if(!s)return!1;if(Or&&s instanceof Or)return!0;const e=Je(s);if(!e||e===Object.prototype||!je(s.append))return!1;const t=hr(s);return t==="formdata"||t==="object"&&je(s.toString)&&s.toString()==="[object FormData]"},jl=Ee("URLSearchParams"),[_l,Sl,kl,Ml]=["ReadableStream","Request","Response","Headers"].map(Ee),Cl=s=>s.trim?s.trim():s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function cs(s,e,{allOwnKeys:t=!1}={}){if(s===null||typeof s>"u")return;let i,n;if(typeof s!="object"&&(s=[s]),at(s))for(i=0,n=s.length;i0;)if(n=t[i],e===n.toLowerCase())return n;return null}const tt=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,pa=s=>!ot(s)&&s!==tt;function Vi(...s){const{caseless:e,skipUndefined:t}=pa(this)&&this||{},i={},n=(a,o)=>{if(o==="__proto__"||o==="constructor"||o==="prototype")return;const l=e&&typeof o=="string"&&ma(i,o)||o,c=ss(i,l)?i[l]:void 0;Ls(c)&&Ls(a)?i[l]=Vi(c,a):Ls(a)?i[l]=Vi({},a):at(a)?i[l]=a.slice():(!t||!ot(a))&&(i[l]=a)};for(let a=0,o=s.length;a(cs(e,(n,a)=>{t&&je(n)?Object.defineProperty(s,a,{__proto__:null,value:oa(n,t),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(s,a,{__proto__:null,value:n,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:i}),s),Tl=s=>(s.charCodeAt(0)===65279&&(s=s.slice(1)),s),Rl=(s,e,t,i)=>{s.prototype=Object.create(e.prototype,i),Object.defineProperty(s.prototype,"constructor",{__proto__:null,value:s,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(s,"super",{__proto__:null,value:e.prototype}),t&&Object.assign(s.prototype,t)},Pl=(s,e,t,i)=>{let n,a,o;const l={};if(e=e||{},s==null)return e;do{for(n=Object.getOwnPropertyNames(s),a=n.length;a-- >0;)o=n[a],(!i||i(o,s,e))&&!l[o]&&(e[o]=s[o],l[o]=!0);s=t!==!1&&Je(s)}while(s&&(!t||t(s,e))&&s!==Object.prototype);return e},Ll=(s,e,t)=>{s=String(s),(t===void 0||t>s.length)&&(t=s.length),t-=e.length;const i=s.indexOf(e,t);return i!==-1&&i===t},Al=s=>{if(!s)return null;if(at(s))return s;let e=s.length;if(!ua(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=s[e];return t},Ol=(s=>e=>s&&e instanceof s)(typeof Uint8Array<"u"&&Je(Uint8Array)),zl=(s,e)=>{const i=(s&&s[ls]).call(s);let n;for(;(n=i.next())&&!n.done;){const a=n.value;e.call(s,a[0],a[1])}},Il=(s,e)=>{let t;const i=[];for(;(t=s.exec(e))!==null;)i.push(t);return i},$l=Ee("HTMLFormElement"),Dl=s=>s.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,i,n){return i.toUpperCase()+n}),{propertyIsEnumerable:Bl}=Object.prototype,Fl=Ee("RegExp"),fa=(s,e)=>{const t=Object.getOwnPropertyDescriptors(s),i={};cs(t,(n,a)=>{let o;(o=e(n,a,s))!==!1&&(i[a]=o||n)}),Object.defineProperties(s,i)},Ul=s=>{fa(s,(e,t)=>{if(je(s)&&["arguments","caller","callee"].includes(t))return!1;const i=s[t];if(je(i)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},ql=(s,e)=>{const t={},i=n=>{n.forEach(a=>{t[a]=!0})};return at(s)?i(s):i(String(s).split(e)),t},Wl=()=>{},Hl=(s,e)=>s!=null&&Number.isFinite(s=+s)?s:e;function Vl(s){return!!(s&&je(s.append)&&s[la]==="FormData"&&s[ls])}const Kl=s=>{const e=new WeakSet,t=i=>{if(zt(i)){if(e.has(i))return;if(Ot(i))return i;if(!("toJSON"in i)){e.add(i);let n;if(vl(i)){n=[];for(const a of i){const o=t(a);!ot(o)&&n.push(o)}}else n=at(i)?[]:{},cs(i,(a,o)=>{const l=t(a);!ot(l)&&(n[o]=l)});return e.delete(i),n}}return i};return t(s)},Gl=Ee("AsyncFunction"),Ql=s=>s&&(zt(s)||je(s))&&je(s.then)&&je(s.catch),xa=((s,e)=>s?setImmediate:e?((t,i)=>(tt.addEventListener("message",({source:n,data:a})=>{n===tt&&a===t&&i.length&&i.shift()()},!1),n=>{i.push(n),tt.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",je(tt.postMessage)),Yl=typeof queueMicrotask<"u"?queueMicrotask.bind(tt):typeof process<"u"&&process.nextTick||xa,ba=s=>s!=null&&je(s[ls]),Jl=s=>s!=null&&is(s,ls)&&ba(s),w={isArray:at,isArrayBuffer:ha,isBuffer:Ot,isFormData:Nl,isArrayBufferView:cl,isString:dl,isNumber:ua,isBoolean:hl,isObject:zt,isPlainObject:Ls,isEmptyObject:ul,isReadableStream:_l,isRequest:Sl,isResponse:kl,isHeaders:Ml,isUndefined:ot,isDate:ml,isFile:pl,isReactNativeBlob:fl,isReactNative:xl,isBlob:bl,isRegExp:Fl,isFunction:je,isStream:yl,isURLSearchParams:jl,isTypedArray:Ol,isFileList:gl,forEach:cs,merge:Vi,extend:El,trim:Cl,stripBOM:Tl,inherits:Rl,toFlatObject:Pl,kindOf:hr,kindOfTest:Ee,endsWith:Ll,toArray:Al,forEachEntry:zl,matchAll:Il,isHTMLForm:$l,hasOwnProperty:ss,hasOwnProp:ss,hasOwnInPrototypeChain:is,getSafeProp:ol,toSafeFlatObject:ll,reduceDescriptors:fa,freezeMethods:Ul,toObjectSet:ql,toCamelCase:Dl,noop:Wl,toFiniteNumber:Hl,findKey:ma,global:tt,isContextDefined:pa,isSpecCompliantForm:Vl,toJSONObject:Kl,isAsyncFn:Gl,isThenable:Ql,setImmediate:xa,asap:Yl,isIterable:ba,isSafeIterable:Jl},Xl=w.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Zl=s=>{const e={};let t,i,n;return s&&s.split(` -`).forEach(function(o){n=o.indexOf(":"),t=o.substring(0,n).trim().toLowerCase(),i=o.substring(n+1).trim();const l=w.hasOwnProp(e,t);!t||l&&w.hasOwnProp(Xl,t)||(t==="set-cookie"?l?e[t].push(i):e[t]=[i]:e[t]=l?e[t]+", "+i:i)}),e};function ec(s){let e=0,t=s.length;for(;ee;){const i=s.charCodeAt(t-1);if(i!==9&&i!==32)break;t-=1}return e===0&&t===s.length?s:s.slice(e,t)}const tc=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),sc=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function ur(s,e){return w.isArray(s)?s.map(t=>ur(t,e)):ec(String(s).replace(e,""))}const ic=s=>ur(s,tc),rc=s=>ur(s,sc);function ga(s){const e=Object.create(null);return w.forEach(s.toJSON(),(t,i)=>{e[i]=rc(t)}),e}const zr=Symbol("internals");function $t(s){return s&&String(s).trim().toLowerCase()}function As(s){return s===!1||s==null?s:w.isArray(s)?s.map(As):ic(String(s))}function nc(s){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=t.exec(s);)e[i[1]]=i[2];return e}const ac=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function gi(s){let e=0,t=s.length;for(;ee;){const i=s.charCodeAt(t-1);if(i!==9&&i!==32)break;t-=1}return e===0&&t===s.length?s:s.slice(e,t)}function oc(s){const e=s.length-1;if(e<1||s.charCodeAt(0)!==34||s.charCodeAt(e)!==34)return s;let t="";for(let i=1;i=e))return s;t+=s[i]}return t}function lc(s){const e=Object.create(null),t=String(s);let i=0,n=!1,a=!1;function o(l){const c=gi(t.slice(i,l)),d=c.indexOf("=");if(d<1)return;const h=gi(c.slice(0,d));if(!ac.test(h))return;const u=h.toLowerCase();if(u==="__proto__"||u==="constructor"||u==="prototype")return;const m=gi(c.slice(d+1));e[u]=oc(m)}for(let l=0;l/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(s.trim());function vi(s,e,t,i,n){if(w.isFunction(i))return i.call(this,e,t);if(n&&(e=t),!!w.isString(e)){if(w.isString(i))return e.indexOf(i)!==-1;if(w.isRegExp(i))return i.test(e)}}function dc(s){return s.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,i)=>t.toUpperCase()+i)}function hc(s,e){const t=w.toCamelCase(" "+e);["get","set","has"].forEach(i=>{Object.defineProperty(s,i+t,{__proto__:null,value:function(n,a,o){return this[i].call(this,e,n,a,o)},configurable:!0})})}let fe=class{constructor(e){e&&this.set(e)}set(e,t,i){const n=this;function a(l,c,d){const h=$t(c);if(!h)return;const u=w.findKey(n,h);(!u||n[u]===void 0||d===!0||d===void 0&&n[u]!==!1)&&(n[u||c]=As(l))}const o=(l,c)=>w.forEach(l,(d,h)=>a(d,h,c));if(w.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(w.isString(e)&&(e=e.trim())&&!cc(e))o(Zl(e),t);else if(w.isObject(e)&&w.isSafeIterable(e)){let l=Object.create(null),c,d;for(const h of e){if(!w.isArray(h))throw new TypeError("Object iterator must return a key-value pair");d=h[0],w.hasOwnProp(l,d)?(c=l[d],l[d]=w.isArray(c)?[...c,h[1]]:[c,h[1]]):l[d]=h[1]}o(l,t)}else e!=null&&a(t,e,i);return this}get(e,t){if(e=$t(e),e){const i=w.findKey(this,e);if(i){const n=this[i];if(!t)return n;if(t===!0)return nc(n);if(w.isFunction(t))return t.call(this,n,i);if(w.isRegExp(t))return t.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=$t(e),e){const i=w.findKey(this,e);return!!(i&&this[i]!==void 0&&(!t||vi(this,this[i],i,t)))}return!1}delete(e,t){const i=this;let n=!1;function a(o){if(o=$t(o),o){const l=w.findKey(i,o);l&&(!t||vi(i,i[l],l,t))&&(delete i[l],n=!0)}}return w.isArray(e)?e.forEach(a):a(e),n}clear(e){const t=Object.keys(this);let i=t.length,n=!1;for(;i--;){const a=t[i];(!e||vi(this,this[a],a,e,!0))&&(delete this[a],n=!0)}return n}normalize(e){const t=this,i={};return w.forEach(this,(n,a)=>{const o=w.findKey(i,a);if(o){t[o]=As(n),delete t[a];return}const l=e?dc(a):String(a).trim();l!==a&&delete t[a],t[l]=As(n),i[l]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return w.forEach(this,(i,n)=>{i!=null&&i!==!1&&(t[n]=e&&w.isArray(i)?i.join(", "):i)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(` -`)}getSetCookie(){const e=this.get("set-cookie");return w.isArray(e)?e:e==null||e===!1?[]:[e]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static parseParameters(e){return lc(e)}static concat(e,...t){const i=new this(e);return t.forEach(n=>i.set(n)),i}static accessor(e){const i=(this[zr]=this[zr]={accessors:{}}).accessors,n=this.prototype;function a(o){const l=$t(o);i[l]||(hc(n,o),i[l]=!0)}return w.isArray(e)?e.forEach(a):a(e),this}};fe.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);w.reduceDescriptors(fe.prototype,({value:s},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>s,set(i){this[t]=i}}});w.freezeMethods(fe);const qs="[REDACTED ****]";function uc(s){if(w.hasOwnProp(s,"toJSON"))return!0;let e=Object.getPrototypeOf(s);for(;e&&e!==Object.prototype;){if(w.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}function mc(s,e){const t=new Set(e.map(a=>String(a).toLowerCase())),i=[],n=a=>{if(a===null||typeof a!="object"||w.isBuffer(a))return a;if(i.indexOf(a)!==-1)return;a instanceof fe&&(a=a.toJSON()),i.push(a);let o;if(w.isArray(a))o=[],a.forEach((l,c)=>{const d=n(l);w.isUndefined(d)||(o[c]=d)});else{if(!w.isPlainObject(a)&&uc(a))return i.pop(),a;o=Object.create(null);for(const[l,c]of Object.entries(a)){const d=t.has(l.toLowerCase())?qs:n(c);w.isUndefined(d)||(o[l]=d)}}return i.pop(),o};return n(s)}function Ir(s){try{return String(s)}catch{return""}}function pc(s){return s.errors.map(t=>{try{return t&&t.message?Ir(t.message):Ir(t)}catch{return""}}).filter(Boolean).join("; ")||s.name||"AggregateError"}let O=class va extends Error{static from(e,t,i,n,a,o){let l=e.message;!l&&w.isArray(e.errors)&&e.errors.length&&(l=pc(e));const c=new va(l,t||e.code,i,n,a);return Object.defineProperty(c,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),c.name=e.name,e.status!=null&&c.status==null&&(c.status=e.status),o&&Object.assign(c,o),c}constructor(e,t,i,n,a){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),a&&(this.response=a,this.status=a.status)}toJSON(){const e=this.config,t=e&&w.hasOwnProp(e,"redact")?e.redact:void 0,i=w.isArray(t)&&t.length>0?mc(e,t):w.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:i,code:this.code,status:this.status}}};O.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";O.ERR_BAD_OPTION="ERR_BAD_OPTION";O.ECONNABORTED="ECONNABORTED";O.ETIMEDOUT="ETIMEDOUT";O.ECONNREFUSED="ECONNREFUSED";O.ERR_NETWORK="ERR_NETWORK";O.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";O.ERR_DEPRECATED="ERR_DEPRECATED";O.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";O.ERR_BAD_REQUEST="ERR_BAD_REQUEST";O.ERR_CANCELED="ERR_CANCELED";O.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";O.ERR_INVALID_URL="ERR_INVALID_URL";O.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const fc=null,ya=100;function Ki(s){return w.isPlainObject(s)||w.isArray(s)}function wa(s){return w.endsWith(s,"[]")?s.slice(0,-2):s}function yi(s,e,t){return s?s.concat(e).map(function(n,a){return n=wa(n),!t&&a?"["+n+"]":n}).join(t?".":""):e}function xc(s){return w.isArray(s)&&!s.some(Ki)}const bc=w.toFlatObject(w,{},null,function(e){return/^is[A-Z]/.test(e)});function si(s,e,t){if(!w.isObject(s))throw new TypeError("target must be an object");e=e||new FormData;const i=(g,S)=>{const j=w.getSafeProp(t,g);return w.isUndefined(j)?S:j},n=i("metaTokens",!0),a=i("visitor")||f,o=i("dots",!1),l=i("indexes",!1),c=i("Blob")||typeof Blob<"u"&&Blob,d=i("maxDepth",ya),h=c&&w.isSpecCompliantForm(e),u=[];if(!w.isFunction(a))throw new TypeError("visitor must be a function");function m(g){if(g===null)return"";if(w.isDate(g))return g.toISOString();if(w.isBoolean(g))return g.toString();if(!h&&w.isBlob(g))throw new O("Blob is not supported. Use a Buffer instead.");if(w.isArrayBuffer(g)||w.isTypedArray(g)){if(h&&typeof c=="function")return new c([g]);throw new O("Blob is not supported. Use a Buffer instead.",O.ERR_NOT_SUPPORT)}return g}function x(g){if(g>d)throw new O("Object is too deeply nested ("+g+" levels). Max depth: "+d,O.ERR_FORM_DATA_DEPTH_EXCEEDED)}function b(g,S){if(d===1/0)return JSON.stringify(g);const j=[];return JSON.stringify(g,function(C,M){if(!w.isObject(M))return M;for(;j.length&&j[j.length-1]!==this;)j.pop();return j.push(M),x(S+j.length-1),M})}function f(g,S,j){let k=g;if(w.isReactNative(e)&&w.isReactNativeBlob(g))return e.append(yi(j,S,o),m(g)),!1;if(g&&!j&&typeof g=="object"){if(w.endsWith(S,"{}"))S=n?S:S.slice(0,-2),g=b(g,1);else if(w.isArray(g)&&xc(g)||(w.isFileList(g)||w.endsWith(S,"[]"))&&(k=w.toArray(g)))return S=wa(S),k.forEach(function(M,L){!(w.isUndefined(M)||M===null)&&e.append(l===!0?yi([S],L,o):l===null?S:S+"[]",m(M))}),!1}return Ki(g)?!0:(e.append(yi(j,S,o),m(g)),!1)}const v=Object.assign(bc,{defaultVisitor:f,convertValue:m,isVisitable:Ki});function p(g,S,j=0){if(!w.isUndefined(g)){if(x(j),u.indexOf(g)!==-1)throw new Error("Circular reference detected in "+S.join("."));u.push(g),w.forEach(g,function(C,M){(!(w.isUndefined(C)||C===null)&&a.call(e,C,w.isString(M)?M.trim():M,S,v))===!0&&p(C,S?S.concat(M):[M],j+1)}),u.pop()}}if(!w.isObject(s))throw new TypeError("data must be an object");return p(s),e}function $r(s){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(s).replace(/[!'()~]|%20/g,function(i){return e[i]})}function mr(s,e){this._pairs=[],s&&si(s,this,e)}const Na=mr.prototype;Na.append=function(e,t){this._pairs.push([e,t])};Na.toString=function(e){const t=e?i=>e.call(this,i,$r):$r;return this._pairs.map(function(n){return t(n[0])+"="+t(n[1])},"").join("&")};function gc(s){return encodeURIComponent(s).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function ja(s,e,t){if(!e)return s;s=s||"";const i=w.isFunction(t)?{serialize:t}:t,n=w.getSafeProp(i,"encode")||gc,a=w.getSafeProp(i,"serialize");let o;if(a?o=a(e,i):o=w.isURLSearchParams(e)?e.toString():new mr(e,i).toString(n),o){const l=s.indexOf("#");l!==-1&&(s=s.slice(0,l)),s+=(s.indexOf("?")===-1?"?":"&")+o}return s}const Dt=Symbol("internals");function _a(s){return s?s.length:0}function Dr(s){if(s)for(;s.length&&s[s.length-1]===null;)s.pop()}function Bt(s,e){const t=s.handlers,i=_a(t);t!==e.handlersRef?(e.handlersRef=t,e.handlerEntries.clear()):i!==e.handlersLength&&(i?e.handlerEntries.forEach(function(a,o){t[a.index]!==a.handler&&e.handlerEntries.delete(o)}):e.handlerEntries.clear()),e.handlersLength=i}class Br{constructor(){this.handlers=[],this[Dt]={handlersRef:this.handlers,handlersLength:this.handlers.length,handlerEntries:new Map,iterationDepth:0,nextId:0}}use(e,t,i){const n={fulfilled:e,rejected:t,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null},a=this[Dt];this.handlers==null&&(this.handlers=[]),Bt(this,a);const o=a.nextId++;return this.handlers.push(n),a.handlerEntries.set(o,{handler:n,index:this.handlers.length-1}),a.handlersLength=this.handlers.length,o}eject(e){const t=this[Dt];Bt(this,t);const i=t.handlerEntries.get(e);if(i){if(t.handlerEntries.delete(e),this.handlers[i.index]!==i.handler)return;this.handlers[i.index]=null,t.iterationDepth||(Dr(this.handlers),t.handlersLength=this.handlers.length)}}clear(){this.handlers&&(this.handlers=[],Bt(this,this[Dt]))}forEach(e){const t=this[Dt];Bt(this,t),t.iterationDepth++;try{w.forEach(this.handlers,function(n){n!==null&&e(n)})}finally{--t.iterationDepth||(Bt(this,t),Dr(this.handlers),t.handlersLength=_a(this.handlers))}}}const pr={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},vc=typeof URLSearchParams<"u"?URLSearchParams:mr,yc=typeof FormData<"u"?FormData:null,wc=typeof Blob<"u"?Blob:null,Nc={isBrowser:!0,classes:{URLSearchParams:vc,FormData:yc,Blob:wc},protocols:["http","https","file","blob","url","data"]},fr=typeof window<"u"&&typeof document<"u",Gi=typeof navigator=="object"&&navigator||void 0,jc=fr&&(!Gi||["ReactNative","NativeScript","NS"].indexOf(Gi.product)<0),_c=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Sc=fr&&window.location.href||"http://localhost",kc=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:fr,hasStandardBrowserEnv:jc,hasStandardBrowserWebWorkerEnv:_c,navigator:Gi,origin:Sc},Symbol.toStringTag,{value:"Module"})),he={...kc,...Nc};function Mc(s,e){return si(s,new he.classes.URLSearchParams,{visitor:function(t,i,n,a){return he.isNode&&w.isBuffer(t)?(this.append(i,t.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...e})}const Fr=ya;function Sa(s){if(s>Fr)throw new O("FormData field is too deeply nested ("+s+" levels). Max depth: "+Fr,O.ERR_FORM_DATA_DEPTH_EXCEEDED)}function Cc(s){const e=[],t=/[^.[\]]+|\[([^.[\]]*)]/g;let i;for(;(i=t.exec(s))!==null;)Sa(e.length),e.push(i[0]==="[]"?"":i[1]||i[0]);return e}function Ec(s){const e={},t=Object.keys(s);let i;const n=t.length;let a;for(i=0;i=t.length;return o=!o&&w.isArray(n)?n.length:o,c?(w.hasOwnProp(n,o)?n[o]=w.isArray(n[o])?n[o].concat(i):[n[o],i]:n[o]=i,!l):((!w.hasOwnProp(n,o)||!w.isObject(n[o]))&&(n[o]=[]),e(t,i,n[o],a)&&w.isArray(n[o])&&(n[o]=Ec(n[o])),!l)}if(w.isFormData(s)&&w.isFunction(s.entries)){const t={};return w.forEachEntry(s,(i,n)=>{e(Cc(i),n,t,0)}),t}return null}const Ma=Object.freeze(["get","delete","head","options","post","put","patch","purge","link","unlink","query"]),bt=(s,e)=>s!=null&&w.hasOwnProp(s,e)?s[e]:void 0;function Tc(s,e,t){if(w.isString(s))try{return(e||JSON.parse)(s),w.trim(s)}catch(i){if(i.name!=="SyntaxError")throw i}return(t||JSON.stringify)(s)}const ds={transitional:pr,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const i=t.getContentType()||"",n=i.indexOf("application/json")>-1,a=w.isObject(e);if(a&&w.isHTMLForm(e)&&(e=new FormData(e)),w.isFormData(e))return n?JSON.stringify(ka(e)):e;if(w.isArrayBuffer(e)||w.isBuffer(e)||w.isStream(e)||w.isFile(e)||w.isBlob(e)||w.isReadableStream(e))return e;if(w.isArrayBufferView(e))return e.buffer;if(w.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let l;if(a){const c=bt(this,"formSerializer");if(i.indexOf("application/x-www-form-urlencoded")>-1)return Mc(e,c).toString();if((l=w.isFileList(e))||i.indexOf("multipart/form-data")>-1){const d=bt(this,"env"),h=d&&d.FormData;return si(l?{"files[]":e}:e,h&&new h,c)}}return a||n?(t.setContentType("application/json",!1),Tc(e)):e}],transformResponse:[function(e){const t=bt(this,"transitional")||ds.transitional,i=t&&t.forcedJSONParsing,n=bt(this,"responseType"),a=n==="json";if(w.isResponse(e)||w.isReadableStream(e))return e;if(e&&w.isString(e)&&(i&&!n||a)){const l=!(t&&t.silentJSONParsing)&&a;try{return JSON.parse(e,bt(this,"parseReviver"))}catch(c){if(l)throw c.name==="SyntaxError"?O.from(c,O.ERR_BAD_RESPONSE,this,null,bt(this,"response")):c}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:he.classes.FormData,Blob:he.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};w.forEach(Ma,s=>{ds.headers[s]={}});function wi(s,e){const t=this||ds,i=e||t,n=fe.from(i.headers);let a=i.data;return w.forEach(s,function(l){a=l.call(t,a,n.normalize(),e?e.status:void 0)}),n.normalize(),a}function Ca(s){return!!(s&&s.__CANCEL__)}let hs=class extends O{constructor(e,t,i){super(e??"canceled",O.ERR_CANCELED,t,i),this.name="CanceledError",this.__CANCEL__=!0}};function Ea(s,e,t){const i=t.config.validateStatus;!t.status||!i||i(t.status)?s(t):e(new O("Request failed with status code "+t.status,t.status>=400&&t.status<500?O.ERR_BAD_REQUEST:O.ERR_BAD_RESPONSE,t.config,t.request,t))}const Rc=/[\t\n\r]/g;function Ta(s){if(typeof s!="string")return s;let e=0;for(;e{t=u,n=null,a&&(clearTimeout(a),a=null),s(...h)};return[(...h)=>{const u=Date.now(),m=u-t;m>=i?o(h,u):(n=h,a||(a=setTimeout(()=>{a=null,o(n)},i-m)))},()=>n&&o(n),(...h)=>o(h)]}const Ws=(s,e,t=3)=>{let i=0;const n=Pc(50,250);return Lc(a=>{if(!a||!w.isNumber(a.loaded))return;const o=a.loaded,l=a.lengthComputable?a.total:void 0,c=Math.max(0,l!=null?Math.min(o,l):o),d=Math.max(0,c-i),h=n(d);i=Math.max(i,c);const u={loaded:c,total:l,progress:l?c/l:void 0,bytes:d,rate:h||void 0,estimated:h&&l?(l-c)/h:void 0,event:a,lengthComputable:l!=null,[e?"download":"upload"]:!0};s(u)},t)},Ur=(s,e)=>{const t=s!=null;return[i=>e[0]({lengthComputable:t,total:s,loaded:i}),e[1]]},qr=(s,e=w.asap)=>(...t)=>e(()=>s(...t)),Ac=he.hasStandardBrowserEnv?((s,e)=>t=>(t=new URL(t,he.origin),s.protocol===t.protocol&&s.host===t.host&&(e||s.port===t.port)))(new URL(he.origin),he.navigator&&/(msie|trident)/i.test(he.navigator.userAgent)):()=>!0,Oc=he.hasStandardBrowserEnv?{write(s,e,t,i,n,a,o){if(typeof document>"u")return;const l=[`${s}=${encodeURIComponent(e)}`];w.isNumber(t)&&l.push(`expires=${new Date(t).toUTCString()}`),w.isString(i)&&l.push(`path=${i}`),w.isString(n)&&l.push(`domain=${n}`),a===!0&&l.push("secure"),w.isString(o)&&l.push(`SameSite=${o}`),document.cookie=l.join("; ")},read(s){if(typeof document>"u")return null;const e=document.cookie.split(";");for(let t=0;t0&&s.charCodeAt(t-1)===47;)t--;return s.slice(0,t)+"/"+e.replace(/^\/+/,"")}const $c=/^https?:(?!\/\/)/i;function Dc(s){return s&&s.replace(/(^|&)([^=&]*=)?[^&]+/g,(e,t,i="")=>`${t}${i}${qs}`)}function Bc(s){const e=s.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${qs}@`),t=e.indexOf("#"),n=(t===-1?e:e.slice(0,t)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${qs}`);return t===-1?n:`${n}#${Dc(e.slice(t+1))}`}function Wr(s,e){if(typeof s=="string"){const t=Ta(s);if($c.test(t))throw new O(`Invalid URL ${JSON.stringify(Bc(t))}: missing "//" after protocol`,O.ERR_INVALID_URL,e)}}function Ra(s,e,t,i){Wr(e,i);let n=!zc(e);return s&&(n||t===!1)?(Wr(s,i),Ic(s,e)):e}const Hr=s=>s instanceof fe?{...s}:s,Fc=s=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(s).concat(Object.getOwnPropertySymbols(s).filter(e=>Object.getOwnPropertyDescriptor(s,e).enumerable)):Object.keys(s);function lt(s,e){s=s||{},e=e||{};const t=Object.create(null);Object.defineProperty(t,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function i(h,u,m,x){return w.isPlainObject(h)&&w.isPlainObject(u)?w.merge.call({caseless:x},h,u):w.isPlainObject(u)?w.merge({},u):w.isArray(u)?u.slice():u}function n(h,u,m,x){if(w.isUndefined(u)){if(!w.isUndefined(h))return i(void 0,h,m,x)}else return i(h,u,m,x)}function a(h,u){if(!w.isUndefined(u))return i(void 0,u)}function o(h,u){if(w.isUndefined(u)){if(!w.isUndefined(h))return i(void 0,h)}else return i(void 0,u)}function l(h){const u=w.hasOwnProp(e,"transitional")?e.transitional:void 0;if(!w.isUndefined(u))if(w.isPlainObject(u)){if(w.hasOwnProp(u,h))return u[h]}else return;const m=w.hasOwnProp(s,"transitional")?s.transitional:void 0;if(w.isPlainObject(m)&&w.hasOwnProp(m,h))return m[h]}function c(h,u,m){if(w.hasOwnProp(e,m))return i(h,u);if(w.hasOwnProp(s,m))return i(void 0,h)}const d={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutErrorMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,allowedSocketPaths:o,responseEncoding:o,validateStatus:c,headers:(h,u,m)=>n(Hr(h),Hr(u),m,!0)};return w.forEach(Fc({...s,...e}),function(u){if(u==="__proto__"||u==="constructor"||u==="prototype")return;const m=w.hasOwnProp(d,u)?d[u]:n,x=w.hasOwnProp(s,u)?s[u]:void 0,b=w.hasOwnProp(e,u)?e[u]:void 0,f=m(x,b,u);w.isUndefined(f)&&m!==c||(t[u]=f)}),w.hasOwnProp(e,"validateStatus")&&w.isUndefined(e.validateStatus)&&l("validateStatusUndefinedResolves")===!1&&(w.hasOwnProp(s,"validateStatus")?t.validateStatus=i(void 0,s.validateStatus):delete t.validateStatus),t}const Uc=["content-type","content-length"];function qc(s,e,t){if(t!=="content-only"){s.set(e);return}Object.entries(e||{}).forEach(([i,n])=>{Uc.includes(i.toLowerCase())&&s.set(i,n)})}const Wc=s=>encodeURIComponent(s).replace(/%([0-9A-F]{2})/gi,(e,t)=>String.fromCharCode(parseInt(t,16)));function Pa(s){const e=lt({},s),t=m=>w.hasOwnProp(e,m)?e[m]:void 0,i=t("data");let n=t("withXSRFToken");const a=t("xsrfHeaderName"),o=t("xsrfCookieName");let l=t("headers");const c=t("auth"),d=t("baseURL"),h=t("allowAbsoluteUrls"),u=t("url");if(e.headers=l=fe.from(l),e.url=ja(Ra(d,u,h,e),t("params"),t("paramsSerializer")),c){const m=w.getSafeProp(c,"username")||"",x=w.getSafeProp(c,"password")||"";try{l.set("Authorization","Basic "+btoa(m+":"+(x?Wc(x):"")))}catch(b){throw O.from(b,O.ERR_BAD_OPTION_VALUE,s)}}if(w.isFormData(i)){const m=w.getSafeProp(i,"getHeaders");he.hasStandardBrowserEnv||he.hasStandardBrowserWebWorkerEnv||w.isReactNative(i)?l.setContentType(void 0):w.isFunction(m)&&qc(l,m.call(i),t("formDataHeaderPolicy"))}if(he.hasStandardBrowserEnv&&(w.isFunction(n)&&(n=n(e)),n===!0||n==null&&Ac(e.url))){const x=a&&o&&Oc.read(o);x&&l.set(a,x)}return e}const Hc=typeof XMLHttpRequest<"u",Vc=Hc&&function(s){return new Promise(function(t,i){const n=Pa(s);let a=n.data;const o=fe.from(n.headers).normalize();let{responseType:l,onUploadProgress:c,onDownloadProgress:d}=n,h,u,m,x,b,f;function v(){x&&x(),b&&b(),n.cancelToken&&n.cancelToken.unsubscribe(h),n.signal&&n.signal.removeEventListener("abort",h)}let p=new XMLHttpRequest;p.open(n.method.toUpperCase(),n.url,!0),p.timeout=n.timeout;function g(j){if(!p)return;if(p.status===0&&(Ni(Ta(n.url))||Ni(he.origin))!=="file"&&!(p.responseURL&&p.responseURL.startsWith("file:"))){i(new O("Request aborted",O.ECONNABORTED,s,p)),v(),p=null;return}try{j?f&&f(j):b&&b()}catch(L){setTimeout(()=>{throw L})}if(!p)return;const k=fe.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),M={data:!l||l==="text"||l==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:k,config:s,request:p};Ea(function(I){t(I),v()},function(I){i(I),v()},M),p=null}"onloadend"in p?p.onloadend=g:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.startsWith("file:"))||setTimeout(g)},p.onabort=function(){p&&(i(new O("Request aborted",O.ECONNABORTED,s,p)),v(),p=null)},p.onerror=function(k){const C=k&&k.message?k.message:"Network Error",M=new O(C,O.ERR_NETWORK,s,p);M.event=k||null,i(M),v(),p=null},p.ontimeout=function(){let k=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const C=n.transitional||pr;n.timeoutErrorMessage&&(k=n.timeoutErrorMessage),i(new O(k,C.clarifyTimeoutError?O.ETIMEDOUT:O.ECONNABORTED,s,p)),v(),p=null},a===void 0&&o.setContentType(null),"setRequestHeader"in p&&w.forEach(ga(o),function(k,C){p.setRequestHeader(C,k)}),w.isUndefined(n.withCredentials)||(p.withCredentials=!!n.withCredentials),l&&l!=="json"&&(p.responseType=n.responseType),d&&([m,b,f]=Ws(d,!0),p.addEventListener("progress",m)),c&&p.upload&&([u,x]=Ws(c),p.upload.addEventListener("progress",u),p.upload.addEventListener("loadend",x)),(n.cancelToken||n.signal)&&(h=j=>{p&&(i(!j||j.type?new hs(null,s,p):j),p.abort(),v(),p=null)},n.cancelToken&&n.cancelToken.subscribe(h),n.signal&&(n.signal.aborted?h():n.signal.addEventListener("abort",h)));const S=Ni(n.url);if(S&&!he.protocols.includes(S)){i(new O("Unsupported protocol "+S+":",O.ERR_BAD_REQUEST,s)),v();return}p.send(a||null)})},Kc=(s,e)=>{if(s=s?s.filter(Boolean):[],!e&&!s.length)return;const t=new AbortController;let i=!1;const n=function(c){if(!i){i=!0,o();const d=c instanceof Error?c:this.reason;t.abort(d instanceof O?d:new hs(d instanceof Error?d.message:d))}};let a=e&&setTimeout(()=>{a=null,n(new O(`timeout of ${e}ms exceeded`,O.ETIMEDOUT))},e);const o=()=>{s&&(a&&clearTimeout(a),a=null,s.forEach(c=>{c.unsubscribe?c.unsubscribe(n):c.removeEventListener("abort",n)}),s=null)};s.forEach(c=>{if(!i){if(c.aborted){n.call(c);return}c.addEventListener("abort",n,{once:!0})}});const{signal:l}=t;return l.unsubscribe=()=>w.asap(o),l},Gc=function*(s,e){let t=s.byteLength;if(t{const n=Qc(s,e);let a=0,o,l=c=>{o||(o=!0,i&&i(c))};return new ReadableStream({async pull(c){try{const{done:d,value:h}=await n.next();if(d){l(),c.close();return}let u=h.byteLength;if(t){let m=a+=u;t(m)}c.enqueue(new Uint8Array(h))}catch(d){throw l(d),d}},cancel(c){return l(c),n.return()}},{highWaterMark:2})},Kr=s=>s>=48&&s<=57||s>=65&&s<=70||s>=97&&s<=102,La=(s,e,t)=>e+2s<=57?s-48:(s&223)-55,Jc=s=>s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||s===43||s===47||s===45||s===95,Xc=s=>s===9||s===10||s===12||s===13||s===32,Zc=s=>{const e=Math.floor(s/4),t=s%4;return e*3+(t===2?1:t===3?2:0)},ed=s=>{const e=s.length;let t=0;return e>0&&s.charCodeAt(e-1)===61&&(t++,e>1&&s.charCodeAt(e-2)===61&&t++),Math.floor((e-t)*3/4)},td=s=>{const e=s.length;let t=0,i=0,n=!1;for(let a=0;a0){n=!0;continue}t++}}return n||i>2||i>0&&(t+i)%4!==0||t%4===1?ed(s):Zc(t)},sd=(s,e)=>{if(!s||typeof s!="string"||!s.startsWith("data:"))return 0;const t=s.indexOf(",");if(t<0)return 0;const i=s.slice(5,t),n=s.slice(t+1);if(/;base64/i.test(i))return e(n);let o=0;for(let l=0,c=n.length;l=55296&&d<=56319&&l+1=56320&&h<=57343?(o+=4,l++):o+=3}else o+=3}return o};function id(s){const e=typeof s=="string"?s.indexOf("#"):-1;return sd(e===-1?s:s.slice(0,e),td)}const xr="1.20.0",Qr=64*1024,rd={cache:"default",redirect:"follow",referrer:"about:client",referrerPolicy:"",mode:"cors",integrity:"",keepalive:!1,priority:"auto",window:null},{isFunction:gs}=w,nd=s=>encodeURIComponent(s).replace(/%([0-9A-F]{2})/gi,(e,t)=>String.fromCharCode(parseInt(t,16))),Yr=s=>{if(!w.isString(s))return s;try{return decodeURIComponent(s)}catch{return s}},Jr=(s,...e)=>{try{return!!s(...e)}catch{return!1}},ad=s=>{const e=s.indexOf("://");let t=s;return e!==-1&&(t=t.slice(e+3)),t.includes("@")||t.includes(":")},od=s=>{const e=w.global!==void 0&&w.global!==null?w.global:globalThis,{ReadableStream:t,TextEncoder:i}=e;s=w.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response},s);const{fetch:n,Request:a,Response:o}=s,l=n?gs(n):typeof fetch=="function",c=gs(a),d=gs(o);if(!l)return!1;const h=l&&gs(t),u=l&&(typeof i=="function"?(p=>g=>p.encode(g))(new i):async p=>new Uint8Array(await new a(p).arrayBuffer())),m=c&&h&&Jr(()=>{let p=!1;const g=new a(he.origin,{body:new t,method:"POST",get duplex(){return p=!0,"half"}}),S=g.headers.has("Content-Type");return g.body!=null&&g.body.cancel(),p&&!S}),x=d&&h&&Jr(()=>w.isReadableStream(new o("").body)),b={stream:x&&(p=>p.body)};l&&["text","arrayBuffer","blob","formData","stream"].forEach(p=>{!b[p]&&(b[p]=(g,S)=>{let j=g&&g[p];if(j)return j.call(g);throw new O(`Response type '${p}' is not supported`,O.ERR_NOT_SUPPORT,S)})});const f=async p=>{if(p==null)return 0;if(w.isBlob(p))return p.size;if(w.isSpecCompliantForm(p))return(await new a(he.origin,{method:"POST",body:p}).arrayBuffer()).byteLength;if(w.isArrayBufferView(p)||w.isArrayBuffer(p))return p.byteLength;if(w.isURLSearchParams(p)&&(p=p+""),w.isString(p))return(await u(p)).byteLength},v=async(p,g)=>{const S=w.toFiniteNumber(p.getContentLength());return S??f(g)};return async p=>{let{url:g,method:S,data:j,signal:k,cancelToken:C,timeout:M,onDownloadProgress:L,onUploadProgress:I,responseType:R,headers:T,withCredentials:E="same-origin",fetchOptions:F,maxContentLength:B,maxBodyLength:z,maxRedirects:V}=Pa(p);const q=w.isNumber(B)&&B>-1,J=w.isNumber(z)&&z>-1,oe=K=>w.hasOwnProp(p,K)?p[K]:void 0;let $=n||fetch;R=R?(R+"").toLowerCase():"text";let W=Kc([k,C&&C.toAbortSignal()],M),N=null;const U=W&&W.unsubscribe&&(()=>{W.unsubscribe()});let A,ee=null;const xe=()=>new O("Request body larger than maxBodyLength limit",O.ERR_BAD_REQUEST,p,N);try{let K;const te=oe("auth");if(te){const H=w.getSafeProp(te,"username")||"",X=w.getSafeProp(te,"password")||"";K={username:H,password:X}}if(ad(g)){const H=new URL(g,he.origin);if(!K&&(H.username||H.password)){const X=Yr(H.username),ke=Yr(H.password);K={username:X,password:ke}}(H.username||H.password)&&(H.username="",H.password="",g=H.href)}if(K&&(T.delete("authorization"),T.set("Authorization","Basic "+btoa(nd((K.username||"")+":"+(K.password||""))))),q&&typeof g=="string"&&g.startsWith("data:")&&id(g)>B)throw new O("maxContentLength size of "+B+" exceeded",O.ERR_BAD_RESPONSE,p,N);if(J&&S!=="get"&&S!=="head"){const H=await f(j);if(typeof H=="number"&&isFinite(H)&&(A=H,H>z))throw xe()}const be=J&&(w.isReadableStream(j)||w.isStream(j)),Se=(H,X,ke)=>Vr(H,Qr,Oe=>{if(J&&Oe>z)throw ee=xe();X&&X(Oe)},ke);if(m&&S!=="get"&&S!=="head"&&(I||be)){if(A=A??await v(T,j),A!==0||be){let H=new a(g,{method:"POST",body:j,duplex:"half"}),X;if(w.isFormData(j)&&(X=H.headers.get("content-type"))&&T.setContentType(X),H.body){const[ke,Oe]=I&&Ur(A,Ws(qr(I)))||[];j=Se(H.body,ke,Oe)}}}else if(be&&!c&&h&&S!=="get"&&S!=="head")j=Se(j);else if(be&&c&&!m&&S!=="get"&&S!=="head")throw new O("Stream request bodies are not supported by the current fetch implementation",O.ERR_NOT_SUPPORT,p,N);w.isString(E)||(E=E?"include":"omit");const Ze=c&&"credentials"in a.prototype;if(w.isFormData(j)){const H=T.getContentType();H&&/^multipart\/form-data/i.test(H)&&!/boundary=/i.test(H)&&T.delete("content-type")}T.set("User-Agent","axios/"+xr,!1);const ge=F==null?F:Object.assign(Object.create(null),F);ge&&(delete ge.body,delete ge.headers,delete ge.method,delete ge.signal,delete ge.duplex,delete ge.credentials);const we=Object.assign(Object.create(null),ge,{signal:W,method:S.toUpperCase(),headers:ga(T.normalize()),body:j,duplex:"half",credentials:Ze?E:void 0});c&&(w.forEach(rd,(H,X)=>{we[X]===void 0&&(we[X]=H)}),we.signal===void 0&&(we.signal=null),we.body===void 0&&(we.body=null)),V===0&&(we.redirect="manual",ge&&(ge.redirect="manual")),N=c&&new a(g,we);let _=await(c?$(N,ge):$(g,we));const Q=fe.from(_.headers);if(q){const H=w.toFiniteNumber(Q.getContentLength());if(H!=null&&H>B)throw new O("maxContentLength size of "+B+" exceeded",O.ERR_BAD_RESPONSE,p,N)}const Y=x&&(R==="stream"||R==="response");if(x&&_.body&&(L||q||Y&&U)){const H={};["status","statusText","headers"].forEach(ze=>{H[ze]=_[ze]});const X=w.toFiniteNumber(Q.getContentLength()),[ke,Oe]=L&&Ur(X,Ws(qr(L),!0))||[];let Ce=0;const xs=ze=>{if(q&&(Ce=ze,Ce>B))throw new O("maxContentLength size of "+B+" exceeded",O.ERR_BAD_RESPONSE,p,N);ke&&ke(ze)};_=new o(Vr(_.body,Qr,xs,()=>{Oe&&Oe(),U&&U()}),H)}R=R||"text";let Z=await b[w.findKey(b,R)||"text"](_,p);if(q&&!x&&!Y){let H;if(Z!=null&&(typeof Z.byteLength=="number"?H=Z.byteLength:typeof Z.size=="number"?H=Z.size:typeof Z=="string"&&(H=typeof i=="function"?new i().encode(Z).byteLength:Z.length)),typeof H=="number"&&H>B)throw new O("maxContentLength size of "+B+" exceeded",O.ERR_BAD_RESPONSE,p,N)}return!Y&&U&&U(),await new Promise((H,X)=>{Ea(H,X,{data:Z,headers:fe.from(_.headers),status:_.status,statusText:_.statusText,config:p,request:N})})}catch(K){if(U&&U(),W&&W.aborted&&W.reason instanceof O){const te=W.reason;throw te.config=p,N&&(te.request=N),K!==te&&Object.defineProperty(te,"cause",{__proto__:null,value:K,writable:!0,enumerable:!1,configurable:!0}),te}if(ee)throw N&&!ee.request&&(ee.request=N),ee;if(K instanceof O)throw N&&!K.request&&(K.request=N),K;if(K&&K.name==="TypeError"&&/Load failed|fetch/i.test(K.message)){const te=new O("Network Error",O.ERR_NETWORK,p,N,K&&K.response);throw Object.defineProperty(te,"cause",{__proto__:null,value:K.cause||K,writable:!0,enumerable:!1,configurable:!0}),te}throw O.from(K,K&&K.code,p,N,K&&K.response)}}},ld=new Map,Aa=s=>{let e=s&&s.env||{};const{fetch:t,Request:i,Response:n}=e,a=[i,n,t];let o=a.length,l=o,c,d,h=ld;for(;l--;)c=a[l],d=h.get(c),d===void 0&&h.set(c,d=l?new Map:od(e)),h=d;return d};Aa();const br={http:fc,xhr:Vc,fetch:{get:Aa}};w.forEach(br,(s,e)=>{if(s){try{Object.defineProperty(s,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(s,"adapterName",{__proto__:null,value:e})}});const Xr=s=>`- ${s}`,cd=s=>w.isFunction(s)||s===null||s===!1;function dd(s,e){s=w.isArray(s)?s:[s];const{length:t}=s;let i,n;const a={};for(let o=0;o`adapter ${c} `+(d===!1?"is not supported by the environment":"is not available in the build"));let l=t?o.length>1?`since : -`+o.map(Xr).join(` -`):" "+Xr(o[0]):"as no adapter specified";throw new O("There is no suitable adapter to dispatch the request "+l,O.ERR_NOT_SUPPORT)}return n}const Oa={getAdapter:dd,adapters:br};function ji(s){if(s.cancelToken&&s.cancelToken.throwIfRequested(),s.signal&&s.signal.aborted)throw new hs(null,s)}function _i(s){const e=w.toSafeFlatObject(s);return ji(e),e.headers=fe.from(w.getSafeProp(e,"headers")),e.data=wi.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Oa.getAdapter(e.adapter||ds.adapter,e)(e).then(function(n){ji(e),e.response=n;try{n.data=wi.call(e,e.transformResponse,n)}finally{delete e.response}return n.headers=fe.from(n.headers),n},function(n){if(!Ca(n)&&(ji(e),n&&n.response)){e.response=n.response;try{n.response.data=wi.call(e,e.transformResponse,n.response)}finally{delete e.response}n.response.headers=fe.from(n.response.headers)}return Promise.reject(n)})}const ii={};["object","boolean","number","function","string","symbol"].forEach((s,e)=>{ii[s]=function(i){return typeof i===s||"a"+(e<1?"n ":" ")+s}});const Zr={};ii.transitional=function(e,t,i){function n(a,o){return"[Axios v"+xr+"] Transitional option '"+a+"'"+o+(i?". "+i:"")}return(a,o,l)=>{if(e===!1)throw new O(n(o," has been removed"+(t?" in "+t:"")),O.ERR_DEPRECATED);return t&&!Zr[o]&&(Zr[o]=!0,console.warn(n(o," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(a,o,l):!0}};ii.spelling=function(e){return(t,i)=>(console.warn(`${i} is likely a misspelling of ${e}`),!0)};function hd(s,e,t){if(typeof s!="object"||s===null)throw new O("options must be an object",O.ERR_BAD_OPTION_VALUE);const i=Object.keys(s);let n=i.length;for(;n-- >0;){const a=i[n],o=Object.prototype.hasOwnProperty.call(e,a)?e[a]:void 0;if(o){const l=s[a],c=l===void 0||o(l,a,s);if(c!==!0)throw new O("option "+a+" must be "+c,O.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new O("Unknown option "+a,O.ERR_BAD_OPTION)}}const Os={assertOptions:hd,validators:ii},pe=Os.validators;let st=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Br,response:new Br}}async request(e,t){try{return await this._request(e,t)}catch(i){if(i instanceof Error)try{let n={};Error.captureStackTrace?Error.captureStackTrace(n):n=new Error;const a=n.stack;let o="";if(typeof a=="string"){const l=a.indexOf(` -`);o=l===-1?"":a.slice(l+1)}if(!i.stack)i.stack=o;else if(o){const l=o.indexOf(` -`),c=l===-1?-1:o.indexOf(` -`,l+1),d=c===-1?"":o.slice(c+1);String(i.stack).endsWith(d)||(i.stack+=` -`+o)}}catch{}throw i}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=lt(this.defaults,t);const{transitional:i,paramsSerializer:n,headers:a}=t;i!==void 0&&Os.assertOptions(i,{silentJSONParsing:pe.transitional(pe.boolean),forcedJSONParsing:pe.transitional(pe.boolean),clarifyTimeoutError:pe.transitional(pe.boolean),legacyInterceptorReqResOrdering:pe.transitional(pe.boolean),advertiseZstdAcceptEncoding:pe.transitional(pe.boolean),validateStatusUndefinedResolves:pe.transitional(pe.boolean)},!1),n!=null&&(w.isFunction(n)?t.paramsSerializer={serialize:n}:Os.assertOptions(n,{encode:pe.function,serialize:pe.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Os.assertOptions(t,{baseUrl:pe.spelling("baseURL"),withXsrfToken:pe.spelling("withXSRFToken")},!0),t.method=(w.getSafeProp(t,"method")||w.getSafeProp(this.defaults,"method")||"get").toLowerCase();let o=a&&w.merge(a.common,a[t.method]);a&&w.forEach(Ma.concat("common"),b=>{delete a[b]}),t.headers=fe.concat(o,a);const l=[];let c=!0;this.interceptors.request.forEach(function(f){if(typeof f.runWhen=="function"&&f.runWhen(t)===!1)return;c=c&&f.synchronous;const v=t.transitional||pr;v&&v.legacyInterceptorReqResOrdering?l.unshift(f.fulfilled,f.rejected):l.push(f.fulfilled,f.rejected)});const d=[];this.interceptors.response.forEach(function(f){d.push(f.fulfilled,f.rejected)});let h,u=0,m;if(!c){const b=[_i.bind(this),void 0];for(b.unshift(...l),b.push(...d),m=b.length,h=Promise.resolve(t);u_i.call(this,x)))}catch(p){h=Promise.reject(p)}break}}if(!h)try{h=_i.call(this,x)}catch(b){h=Promise.reject(b)}for(u=0,m=d.length;u{if(!i._listeners)return;let a=i._listeners.length;for(;a-- >0;)i._listeners[a](n);i._listeners=null}),this.promise.then=n=>{let a;const o=new Promise(l=>{i.subscribe(l),a=l}).then(n);return o.cancel=function(){i.unsubscribe(a)},o},e(function(a,o,l){i.reason||(i.reason=new hs(a,o,l),t(i.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=i=>{e.abort(i)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new za(function(n){e=n}),cancel:e}}};function md(s){return function(t){return s.apply(null,t)}}function pd(s){return w.isObject(s)&&s.isAxiosError===!0}const zs={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(zs).forEach(([s,e])=>{zs[e]===void 0&&(zs[e]=s)});function Ia(s){const e=new st(s),t=oa(st.prototype.request,e);return w.extend(t,st.prototype,e,{allOwnKeys:!0}),w.extend(t,e,null,{allOwnKeys:!0}),t.create=function(n){return Ia(lt(s,n))},t}const ce=Ia(ds);ce.Axios=st;ce.CanceledError=hs;ce.CancelToken=ud;ce.isCancel=Ca;ce.VERSION=xr;ce.toFormData=si;ce.AxiosError=O;ce.Cancel=ce.CanceledError;ce.all=function(e){return Promise.all(e)};ce.spread=md;ce.isAxiosError=pd;ce.mergeConfig=lt;ce.AxiosHeaders=fe;ce.formToJSON=s=>ka(w.isHTMLForm(s)?new FormData(s):s);ce.getAdapter=Oa.getAdapter;ce.HttpStatusCode=zs;ce.default=ce;const{Axios:mf,AxiosError:pf,CanceledError:ff,isCancel:xf,CancelToken:bf,VERSION:gf,all:vf,Cancel:yf,isAxiosError:wf,spread:Nf,toFormData:jf,AxiosHeaders:_f,HttpStatusCode:Sf,formToJSON:kf,getAdapter:Mf,mergeConfig:Cf,create:Ef}=ce,fd="https://agus1111-perps-terminal.hf.space",Qi="perps_api_token";function xd(){if(typeof window<"u"){const s=localStorage.getItem(Qi);if(s)return s.trim()}return""}function Tf(s){const e=s.trim();typeof window<"u"&&(e?localStorage.setItem(Qi,e):localStorage.removeItem(Qi),window.dispatchEvent(new Event("perps_api_token_changed")))}function bd(){return typeof window>"u"?!1:!!(window.Capacitor?.isNativePlatform?.()||window.Capacitor||window.location.hostname==="localhost"&&window.location.port==="")}function ri(){if(typeof window<"u"){const s=localStorage.getItem("perps_server_url");if(s)return s.trim().replace(/\/+$/,"")}return bd()?fd:typeof window<"u"&&window.location.port==="5173"?"http://127.0.0.1:8000":""}function Rf(s){const e=s.trim().replace(/\/+$/,"");e?localStorage.setItem("perps_server_url",e):localStorage.removeItem("perps_server_url"),typeof window<"u"&&window.dispatchEvent(new Event("perps_server_url_changed"))}const gd=ri(),ie=ce.create({baseURL:gd,timeout:0,headers:{"Content-Type":"application/json"}});ie.interceptors.request.use(s=>{const e=ri();e&&(s.baseURL=e);const t=xd();return t&&s.headers.set("Authorization",`Bearer ${t}`),s});ie.interceptors.response.use(s=>s,s=>{const e=s.response?.status,t=s.response?.data?.detail||s.response?.data?.message||s.message||"An unexpected error occurred",i=Object.assign(new Error(t),{status:e});return Promise.reject(i)});function Vt(){const s=ri();if(s){const e=s.startsWith("https://")?"wss://":"ws://",t=s.replace(/^https?:\/\//,"");return`${e}${t}/ws/signals`}return typeof window<"u"?window.location.port==="5173"?"ws://127.0.0.1:8000/ws/signals":`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/signals`:null}function vd(s){const e=s.toUpperCase().replace("/","").replace("-",""),t=ri();if(t){const i=t.startsWith("https://")?"wss://":"ws://",n=t.replace(/^https?:\/\//,"");return`${i}${n}/ws/chart/${e}`}return typeof window<"u"?window.location.port==="5173"?`ws://127.0.0.1:8000/ws/chart/${e}`:`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/chart/${e}`:null}const Yi=Vt(),ni={getAll:async()=>{const{data:s}=await ie.get("/api/pairs");return s},validate:async s=>{const{data:e}=await ie.post("/api/pairs/validate",{symbol:s});return e},add:async s=>{const{data:e}=await ie.post("/api/pairs",{symbol:s});return e},remove:async s=>{await ie.delete(`/api/pairs/${s}`)},toggleActive:async(s,e)=>{const{data:t}=await ie.patch(`/api/pairs/${s}/toggle`,{is_active:e});return t}},ai=["pairs"];function us(){return Zt({queryKey:ai,queryFn:ni.getAll,placeholderData:s=>s,refetchInterval:6e4,refetchOnWindowFocus:!1,retry:3,staleTime:6e4})}function Pf(){const s=os();return as({mutationFn:e=>ni.add(e),onSuccess:()=>{s.invalidateQueries({queryKey:ai}),s.invalidateQueries({queryKey:["signals"]})}})}function yd(){const s=os();return as({mutationFn:e=>ni.remove(e),onSuccess:()=>{s.invalidateQueries({queryKey:ai}),s.invalidateQueries({queryKey:["signals"]})}})}function Lf(){return as({mutationFn:s=>ni.validate(s)})}function $a(s){var e,t,i="";if(typeof s=="string"||typeof s=="number")i+=s;else if(typeof s=="object")if(Array.isArray(s)){var n=s.length;for(e=0;e{const e=jd(s),{conflictingClassGroups:t,conflictingClassGroupModifiers:i}=s;return{getClassGroupId:o=>{const l=o.split(gr);return l[0]===""&&l.length!==1&&l.shift(),Da(l,e)||Nd(o)},getConflictingClassGroupIds:(o,l)=>{const c=t[o]||[];return l&&i[o]?[...c,...i[o]]:c}}},Da=(s,e)=>{if(s.length===0)return e.classGroupId;const t=s[0],i=e.nextPart.get(t),n=i?Da(s.slice(1),i):void 0;if(n)return n;if(e.validators.length===0)return;const a=s.join(gr);return e.validators.find(({validator:o})=>o(a))?.classGroupId},en=/^\[(.+)\]$/,Nd=s=>{if(en.test(s)){const e=en.exec(s)[1],t=e?.substring(0,e.indexOf(":"));if(t)return"arbitrary.."+t}},jd=s=>{const{theme:e,prefix:t}=s,i={nextPart:new Map,validators:[]};return Sd(Object.entries(s.classGroups),t).forEach(([a,o])=>{Ji(o,i,a,e)}),i},Ji=(s,e,t,i)=>{s.forEach(n=>{if(typeof n=="string"){const a=n===""?e:tn(e,n);a.classGroupId=t;return}if(typeof n=="function"){if(_d(n)){Ji(n(i),e,t,i);return}e.validators.push({validator:n,classGroupId:t});return}Object.entries(n).forEach(([a,o])=>{Ji(o,tn(e,a),t,i)})})},tn=(s,e)=>{let t=s;return e.split(gr).forEach(i=>{t.nextPart.has(i)||t.nextPart.set(i,{nextPart:new Map,validators:[]}),t=t.nextPart.get(i)}),t},_d=s=>s.isThemeGetter,Sd=(s,e)=>e?s.map(([t,i])=>{const n=i.map(a=>typeof a=="string"?e+a:typeof a=="object"?Object.fromEntries(Object.entries(a).map(([o,l])=>[e+o,l])):a);return[t,n]}):s,kd=s=>{if(s<1)return{get:()=>{},set:()=>{}};let e=0,t=new Map,i=new Map;const n=(a,o)=>{t.set(a,o),e++,e>s&&(e=0,i=t,t=new Map)};return{get(a){let o=t.get(a);if(o!==void 0)return o;if((o=i.get(a))!==void 0)return n(a,o),o},set(a,o){t.has(a)?t.set(a,o):n(a,o)}}},Ba="!",Md=s=>{const{separator:e,experimentalParseClassName:t}=s,i=e.length===1,n=e[0],a=e.length,o=l=>{const c=[];let d=0,h=0,u;for(let v=0;vh?u-h:void 0;return{modifiers:c,hasImportantModifier:x,baseClassName:b,maybePostfixModifierPosition:f}};return t?l=>t({className:l,parseClassName:o}):o},Cd=s=>{if(s.length<=1)return s;const e=[];let t=[];return s.forEach(i=>{i[0]==="["?(e.push(...t.sort(),i),t=[]):t.push(i)}),e.push(...t.sort()),e},Ed=s=>({cache:kd(s.cacheSize),parseClassName:Md(s),...wd(s)}),Td=/\s+/,Rd=(s,e)=>{const{parseClassName:t,getClassGroupId:i,getConflictingClassGroupIds:n}=e,a=[],o=s.trim().split(Td);let l="";for(let c=o.length-1;c>=0;c-=1){const d=o[c],{modifiers:h,hasImportantModifier:u,baseClassName:m,maybePostfixModifierPosition:x}=t(d);let b=!!x,f=i(b?m.substring(0,x):m);if(!f){if(!b){l=d+(l.length>0?" "+l:l);continue}if(f=i(m),!f){l=d+(l.length>0?" "+l:l);continue}b=!1}const v=Cd(h).join(":"),p=u?v+Ba:v,g=p+f;if(a.includes(g))continue;a.push(g);const S=n(f,b);for(let j=0;j0?" "+l:l)}return l};function Pd(){let s=0,e,t,i="";for(;s{if(typeof s=="string")return s;let e,t="";for(let i=0;iu(h),s());return t=Ed(d),i=t.cache.get,n=t.cache.set,a=l,l(c)}function l(c){const d=i(c);if(d)return d;const h=Rd(c,t);return n(c,h),h}return function(){return a(Pd.apply(null,arguments))}}const ne=s=>{const e=t=>t[s]||[];return e.isThemeGetter=!0,e},Ua=/^\[(?:([a-z-]+):)?(.+)\]$/i,Ad=/^\d+\/\d+$/,Od=new Set(["px","full","screen"]),zd=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Id=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,$d=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Dd=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Bd=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ie=s=>_t(s)||Od.has(s)||Ad.test(s),qe=s=>It(s,"length",Gd),_t=s=>!!s&&!Number.isNaN(Number(s)),Si=s=>It(s,"number",_t),Ft=s=>!!s&&Number.isInteger(Number(s)),Fd=s=>s.endsWith("%")&&_t(s.slice(0,-1)),G=s=>Ua.test(s),We=s=>zd.test(s),Ud=new Set(["length","size","percentage"]),qd=s=>It(s,Ud,qa),Wd=s=>It(s,"position",qa),Hd=new Set(["image","url"]),Vd=s=>It(s,Hd,Yd),Kd=s=>It(s,"",Qd),Ut=()=>!0,It=(s,e,t)=>{const i=Ua.exec(s);return i?i[1]?typeof e=="string"?i[1]===e:e.has(i[1]):t(i[2]):!1},Gd=s=>Id.test(s)&&!$d.test(s),qa=()=>!1,Qd=s=>Dd.test(s),Yd=s=>Bd.test(s),Jd=()=>{const s=ne("colors"),e=ne("spacing"),t=ne("blur"),i=ne("brightness"),n=ne("borderColor"),a=ne("borderRadius"),o=ne("borderSpacing"),l=ne("borderWidth"),c=ne("contrast"),d=ne("grayscale"),h=ne("hueRotate"),u=ne("invert"),m=ne("gap"),x=ne("gradientColorStops"),b=ne("gradientColorStopPositions"),f=ne("inset"),v=ne("margin"),p=ne("opacity"),g=ne("padding"),S=ne("saturate"),j=ne("scale"),k=ne("sepia"),C=ne("skew"),M=ne("space"),L=ne("translate"),I=()=>["auto","contain","none"],R=()=>["auto","hidden","clip","visible","scroll"],T=()=>["auto",G,e],E=()=>[G,e],F=()=>["",Ie,qe],B=()=>["auto",_t,G],z=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],V=()=>["solid","dashed","dotted","double","none"],q=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>["start","end","center","between","around","evenly","stretch"],oe=()=>["","0",G],$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],W=()=>[_t,G];return{cacheSize:500,separator:":",theme:{colors:[Ut],spacing:[Ie,qe],blur:["none","",We,G],brightness:W(),borderColor:[s],borderRadius:["none","","full",We,G],borderSpacing:E(),borderWidth:F(),contrast:W(),grayscale:oe(),hueRotate:W(),invert:oe(),gap:E(),gradientColorStops:[s],gradientColorStopPositions:[Fd,qe],inset:T(),margin:T(),opacity:W(),padding:E(),saturate:W(),scale:W(),sepia:oe(),skew:W(),space:E(),translate:E()},classGroups:{aspect:[{aspect:["auto","square","video",G]}],container:["container"],columns:[{columns:[We]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...z(),G]}],overflow:[{overflow:R()}],"overflow-x":[{"overflow-x":R()}],"overflow-y":[{"overflow-y":R()}],overscroll:[{overscroll:I()}],"overscroll-x":[{"overscroll-x":I()}],"overscroll-y":[{"overscroll-y":I()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[f]}],"inset-x":[{"inset-x":[f]}],"inset-y":[{"inset-y":[f]}],start:[{start:[f]}],end:[{end:[f]}],top:[{top:[f]}],right:[{right:[f]}],bottom:[{bottom:[f]}],left:[{left:[f]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Ft,G]}],basis:[{basis:T()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",G]}],grow:[{grow:oe()}],shrink:[{shrink:oe()}],order:[{order:["first","last","none",Ft,G]}],"grid-cols":[{"grid-cols":[Ut]}],"col-start-end":[{col:["auto",{span:["full",Ft,G]},G]}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":[Ut]}],"row-start-end":[{row:["auto",{span:[Ft,G]},G]}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",G]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",G]}],gap:[{gap:[m]}],"gap-x":[{"gap-x":[m]}],"gap-y":[{"gap-y":[m]}],"justify-content":[{justify:["normal",...J()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...J(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...J(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[g]}],px:[{px:[g]}],py:[{py:[g]}],ps:[{ps:[g]}],pe:[{pe:[g]}],pt:[{pt:[g]}],pr:[{pr:[g]}],pb:[{pb:[g]}],pl:[{pl:[g]}],m:[{m:[v]}],mx:[{mx:[v]}],my:[{my:[v]}],ms:[{ms:[v]}],me:[{me:[v]}],mt:[{mt:[v]}],mr:[{mr:[v]}],mb:[{mb:[v]}],ml:[{ml:[v]}],"space-x":[{"space-x":[M]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[M]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",G,e]}],"min-w":[{"min-w":[G,e,"min","max","fit"]}],"max-w":[{"max-w":[G,e,"none","full","min","max","fit","prose",{screen:[We]},We]}],h:[{h:[G,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[G,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[G,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[G,e,"auto","min","max","fit"]}],"font-size":[{text:["base",We,qe]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Si]}],"font-family":[{font:[Ut]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",G]}],"line-clamp":[{"line-clamp":["none",_t,Si]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Ie,G]}],"list-image":[{"list-image":["none",G]}],"list-style-type":[{list:["none","disc","decimal",G]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[p]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[p]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...V(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Ie,qe]}],"underline-offset":[{"underline-offset":["auto",Ie,G]}],"text-decoration-color":[{decoration:[s]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:E()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",G]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",G]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[p]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...z(),Wd]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",qd]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Vd]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[b]}],"gradient-via-pos":[{via:[b]}],"gradient-to-pos":[{to:[b]}],"gradient-from":[{from:[x]}],"gradient-via":[{via:[x]}],"gradient-to":[{to:[x]}],rounded:[{rounded:[a]}],"rounded-s":[{"rounded-s":[a]}],"rounded-e":[{"rounded-e":[a]}],"rounded-t":[{"rounded-t":[a]}],"rounded-r":[{"rounded-r":[a]}],"rounded-b":[{"rounded-b":[a]}],"rounded-l":[{"rounded-l":[a]}],"rounded-ss":[{"rounded-ss":[a]}],"rounded-se":[{"rounded-se":[a]}],"rounded-ee":[{"rounded-ee":[a]}],"rounded-es":[{"rounded-es":[a]}],"rounded-tl":[{"rounded-tl":[a]}],"rounded-tr":[{"rounded-tr":[a]}],"rounded-br":[{"rounded-br":[a]}],"rounded-bl":[{"rounded-bl":[a]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[p]}],"border-style":[{border:[...V(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[p]}],"divide-style":[{divide:V()}],"border-color":[{border:[n]}],"border-color-x":[{"border-x":[n]}],"border-color-y":[{"border-y":[n]}],"border-color-s":[{"border-s":[n]}],"border-color-e":[{"border-e":[n]}],"border-color-t":[{"border-t":[n]}],"border-color-r":[{"border-r":[n]}],"border-color-b":[{"border-b":[n]}],"border-color-l":[{"border-l":[n]}],"divide-color":[{divide:[n]}],"outline-style":[{outline:["",...V()]}],"outline-offset":[{"outline-offset":[Ie,G]}],"outline-w":[{outline:[Ie,qe]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:F()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[p]}],"ring-offset-w":[{"ring-offset":[Ie,qe]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",We,Kd]}],"shadow-color":[{shadow:[Ut]}],opacity:[{opacity:[p]}],"mix-blend":[{"mix-blend":[...q(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":q()}],filter:[{filter:["","none"]}],blur:[{blur:[t]}],brightness:[{brightness:[i]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",We,G]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[u]}],saturate:[{saturate:[S]}],sepia:[{sepia:[k]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[t]}],"backdrop-brightness":[{"backdrop-brightness":[i]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[u]}],"backdrop-opacity":[{"backdrop-opacity":[p]}],"backdrop-saturate":[{"backdrop-saturate":[S]}],"backdrop-sepia":[{"backdrop-sepia":[k]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[o]}],"border-spacing-x":[{"border-spacing-x":[o]}],"border-spacing-y":[{"border-spacing-y":[o]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",G]}],duration:[{duration:W()}],ease:[{ease:["linear","in","out","in-out",G]}],delay:[{delay:W()}],animate:[{animate:["none","spin","ping","pulse","bounce",G]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[j]}],"scale-x":[{"scale-x":[j]}],"scale-y":[{"scale-y":[j]}],rotate:[{rotate:[Ft,G]}],"translate-x":[{"translate-x":[L]}],"translate-y":[{"translate-y":[L]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",G]}],accent:[{accent:["auto",s]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",G]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":E()}],"scroll-mx":[{"scroll-mx":E()}],"scroll-my":[{"scroll-my":E()}],"scroll-ms":[{"scroll-ms":E()}],"scroll-me":[{"scroll-me":E()}],"scroll-mt":[{"scroll-mt":E()}],"scroll-mr":[{"scroll-mr":E()}],"scroll-mb":[{"scroll-mb":E()}],"scroll-ml":[{"scroll-ml":E()}],"scroll-p":[{"scroll-p":E()}],"scroll-px":[{"scroll-px":E()}],"scroll-py":[{"scroll-py":E()}],"scroll-ps":[{"scroll-ps":E()}],"scroll-pe":[{"scroll-pe":E()}],"scroll-pt":[{"scroll-pt":E()}],"scroll-pr":[{"scroll-pr":E()}],"scroll-pb":[{"scroll-pb":E()}],"scroll-pl":[{"scroll-pl":E()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",G]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[Ie,qe,Si]}],stroke:[{stroke:[s,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},ps=Ld(Jd);function Xd(...s){return ps(ms(s))}const Wa=y.createContext(null);function ft(){const s=y.useContext(Wa);if(!s)throw new Error("useToast must be used within ToastProvider");return s}function Zd({children:s}){const[e,t]=y.useState([]),i=y.useCallback((a,o="info")=>{const l=Math.random().toString(36).slice(2);t(c=>[...c,{id:l,message:a,variant:o}]),setTimeout(()=>{t(c=>c.filter(d=>d.id!==l))},4e3)},[]),n=y.useCallback(a=>{t(o=>o.filter(l=>l.id!==a))},[]);return r.jsxs(Wa.Provider,{value:{toast:i},children:[s,r.jsx("div",{className:"fixed bottom-4 right-4 z-[100] flex flex-col gap-2 pointer-events-none",children:e.map(a=>r.jsx(th,{item:a,onRemove:n},a.id))})]})}const eh={success:{icon:r.jsx(sa,{size:16}),cls:"border-signal-long/30 text-signal-long"},error:{icon:r.jsx(ar,{size:16}),cls:"border-signal-short/30 text-signal-short"},info:{icon:r.jsx(Ao,{size:16}),cls:"border-accent-blue/30 text-accent-blue"}};function th({item:s,onRemove:e}){const[t,i]=y.useState(!1),n=eh[s.variant];return y.useEffect(()=>{requestAnimationFrame(()=>i(!0))},[]),r.jsxs("div",{className:Xd("pointer-events-auto flex items-center gap-3 bg-bg-card border rounded-lg px-4 py-3 shadow-xl","transition-all duration-300",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",n.cls),style:{minWidth:"280px",maxWidth:"400px"},children:[n.icon,r.jsx("p",{className:"text-sm text-text-primary flex-1",children:s.message}),r.jsx("button",{onClick:()=>e(s.id),className:"text-text-secondary hover:text-text-primary transition-colors",children:r.jsx(Ct,{size:14})})]})}function Hs({pair:s,signal:e,isSelected:t,onSelect:i}){const{mutate:n,isPending:a}=yd(),{toast:o}=ft(),l=u=>{u.stopPropagation(),n(s.id,{onSuccess:()=>o(`${s.symbol} removed`,"info"),onError:m=>o(m.message,"error")})},c=e?.streak??s.streak_count??0,d=s.symbol.replace(/(USDT|USDC|PERP)$/,""),h=s.symbol.slice(d.length)||"USDT";return r.jsxs("div",{className:`group relative flex flex-col gap-1.5 px-3 py-2.5 rounded-lg cursor-pointer transition-colors - ${t?"bg-accent-blue/10 border border-accent-blue/30":"hover:bg-bg-elevated border border-transparent"} - ${s.is_active?"":"opacity-50"} - `,onClick:()=>i(s.symbol),children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${s.is_active?"bg-signal-long":"bg-text-muted"}`}),r.jsxs("div",{className:"flex items-baseline gap-0.5 flex-1 min-w-0",children:[r.jsx("span",{className:"font-mono text-sm font-bold text-text-primary whitespace-nowrap",children:d}),r.jsxs("span",{className:"font-mono text-[10px] text-text-muted/70",children:["/",h]})]}),c>=2&&r.jsxs("span",{className:"text-[10px] font-mono font-bold px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-400 border border-amber-500/30 shrink-0 flex items-center gap-0.5 animate-pulse",title:`Consistent Streak: ${c}x cycles`,children:["🔥 ",c,"x"]}),e&&r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx(dr,{direction:e.direction,size:"sm"}),r.jsx("span",{className:`text-[10px] font-mono font-bold px-1.5 py-0.5 rounded border ${e.conviction>=6?"bg-signal-long/15 text-signal-long border-signal-long/30":e.conviction>=3?"bg-accent-blue/15 text-accent-blue border-accent-blue/30":"bg-bg-elevated text-text-muted border-border"}`,title:`Conviction: ${e.conviction}/10`,children:e.conviction})]}),r.jsx("button",{onClick:l,disabled:a,className:"opacity-70 sm:opacity-0 sm:group-hover:opacity-100 p-1 rounded text-text-muted hover:text-signal-short transition-all shrink-0 active:scale-90",title:"Remove pair",children:r.jsx(Ct,{size:13})})]}),r.jsxs("div",{className:"flex items-center justify-between pl-4 text-[10px]",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsxs("span",{className:`flex items-center gap-0.5 font-mono ${s.on_binance?"text-signal-long font-medium":"text-text-muted/40"}`,title:`Binance: ${s.on_binance?"Available":"Unavailable"}`,children:[s.on_binance?"✓":"○"," Bin"]}),r.jsxs("span",{className:`flex items-center gap-0.5 font-mono ${s.on_bybit?"text-signal-long font-medium":"text-text-muted/40"}`,title:`Bybit: ${s.on_bybit?"Available":"Unavailable"}`,children:[s.on_bybit?"✓":"○"," Byb"]}),r.jsxs("span",{className:`flex items-center gap-0.5 font-mono ${s.on_okx?"text-signal-long font-medium":"text-text-muted/40"}`,title:`OKX: ${s.on_okx?"Available":"Unavailable"}`,children:[s.on_okx?"✓":"○"," OKX"]}),r.jsxs("span",{className:`flex items-center gap-0.5 font-mono ${s.on_bitget?"text-signal-long font-medium":"text-text-muted/40"}`,title:`Bitget: ${s.on_bitget?"Available":"Unavailable"}`,children:[s.on_bitget?"✓":"○"," Bit"]}),r.jsxs("span",{className:`flex items-center gap-0.5 font-mono ${s.on_hyperliquid?"text-signal-long font-medium":"text-text-muted/40"}`,title:`Hyperliquid: ${s.on_hyperliquid?"Available":"Unavailable"}`,children:[s.on_hyperliquid?"✓":"○"," HL"]})]}),e&&e.has_spot===!0&&r.jsx("span",{className:"text-[9px] font-mono text-emerald-400 font-medium shrink-0 ml-1",children:"🛡️ Spot"}),e&&e.has_spot===!1&&r.jsx("span",{className:"text-[9px] font-mono text-amber-400 font-bold shrink-0 ml-1",children:"⚠️ Perp"})]})]})}function Ha(...s){return ps(ms(s))}const sh={sm:"w-4 h-4 border-2",md:"w-6 h-6 border-2",lg:"w-10 h-10 border-3"};function sn({size:s="md",className:e}){return r.jsx("div",{className:Ha("rounded-full border-accent-blue border-t-transparent animate-spin",sh[s],e)})}function Te({className:s}){return r.jsx("div",{className:Ha("skeleton",s)})}function ih(){return r.jsxs("div",{className:"card p-5 space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx(Te,{className:"h-5 w-24"}),r.jsx(Te,{className:"h-6 w-16 rounded-full"})]}),r.jsx(Te,{className:"h-4 w-32"}),r.jsx(Te,{className:"h-3 w-full rounded-full"}),r.jsx("div",{className:"space-y-2",children:[...Array(4)].map((s,e)=>r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx(Te,{className:"h-3 w-28"}),r.jsx(Te,{className:"h-3 w-16"})]},e))})]})}function rh({pairs:s,signals:e,isLoading:t,selectedSymbol:i,onSelect:n}){const a=new Map(e.map(c=>[c.symbol,c]));if(t)return r.jsx("div",{className:"space-y-2 px-2",children:[...Array(4)].map((c,d)=>r.jsxs("div",{className:"space-y-1.5 px-3 py-2.5",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Te,{className:"w-2 h-2 rounded-full"}),r.jsx(Te,{className:"h-4 flex-1"})]}),r.jsx(Te,{className:"h-3 w-28 ml-4"})]},d))});if(s.length===0)return r.jsx("div",{className:"px-3 py-4 text-center",children:r.jsx("p",{className:"text-xs text-text-muted",children:"No pairs added yet"})});const o=[...s.filter(c=>c.is_active)].sort((c,d)=>c.symbol.localeCompare(d.symbol)),l=s.filter(c=>!c.is_active);return r.jsxs("div",{className:"space-y-1 px-2",children:[o.map(c=>r.jsx(Hs,{pair:c,signal:a.get(c.symbol),isSelected:i===c.symbol,onSelect:n},c.id)),l.length>0&&r.jsxs(r.Fragment,{children:[o.length>0&&r.jsx("div",{className:"px-3 pt-3 pb-1",children:r.jsx("p",{className:"text-[10px] uppercase tracking-widest text-text-muted font-medium",children:"Inactive"})}),l.map(c=>r.jsx(Hs,{pair:c,signal:a.get(c.symbol),isSelected:i===c.symbol,onSelect:n},c.id))]})]})}function nh(...s){return ps(ms(s))}const ah={primary:"bg-accent-blue hover:bg-blue-600 text-white border-transparent",ghost:"bg-transparent hover:bg-bg-elevated text-text-secondary hover:text-text-primary border-border",danger:"bg-transparent hover:bg-signal-short-bg text-signal-short border-signal-short/30 hover:border-signal-short/60",success:"bg-transparent hover:bg-signal-long-bg text-signal-long border-signal-long/30 hover:border-signal-long/60"},oh={sm:"text-xs px-2.5 py-1.5 gap-1",md:"text-sm px-4 py-2 gap-2",lg:"text-base px-5 py-2.5 gap-2"};function se({variant:s="ghost",size:e="md",loading:t=!1,icon:i,children:n,className:a,disabled:o,...l}){return r.jsxs("button",{className:nh("inline-flex items-center justify-center font-medium rounded-lg border","transition-colors duration-150 cursor-pointer","disabled:opacity-50 disabled:cursor-not-allowed",ah[s],oh[e],a),disabled:o||t,...l,children:[t?r.jsx("span",{className:"w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"}):i||null,n]})}const lh=y.lazy(()=>pt(()=>import("./AddPairModal-D8YkLLF_.js"),__vite__mapDeps([0,1,2,3])).then(s=>({default:s.AddPairModal})));function ch({pairs:s,signals:e,isLoading:t,selectedSymbol:i,onSelect:n}){const[a,o]=y.useState(!1),l=s.filter(c=>c.is_active).length;return r.jsxs(r.Fragment,{children:[r.jsxs("aside",{className:"w-64 lg:w-72 xl:w-80 shrink-0 flex flex-col border-r border-border bg-bg-card overflow-hidden",children:[r.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ia,{size:14,className:"text-accent-blue"}),r.jsx("span",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wider",children:"Pairs"})]}),l>0&&r.jsxs("span",{className:"text-[10px] font-mono bg-accent-blue/10 text-accent-blue border border-accent-blue/20 px-1.5 py-0.5 rounded",children:[l," active"]})]}),r.jsx(se,{variant:"primary",size:"sm",onClick:()=>o(!0),icon:r.jsx(or,{size:13}),className:"w-full justify-center",children:"Add Pair"})]}),r.jsx("div",{className:"flex-1 overflow-y-auto py-2",children:r.jsx(rh,{pairs:s,signals:e,isLoading:t,selectedSymbol:i,onSelect:n})}),r.jsx("div",{className:"px-4 py-3 border-t border-border",children:r.jsx("div",{className:"grid grid-cols-3 gap-2 text-center",children:["LONG","SHORT","NEUTRAL"].map(c=>{const d=e.filter(h=>h.direction===c).length;return r.jsxs("div",{children:[r.jsx("p",{className:`text-sm font-bold font-mono ${c==="LONG"?"text-signal-long":c==="SHORT"?"text-signal-short":"text-text-muted"}`,children:d}),r.jsx("p",{className:"text-[10px] text-text-muted",children:c})]},c)})})})]}),a&&r.jsx(y.Suspense,{fallback:null,children:r.jsx(lh,{isOpen:a,onClose:()=>o(!1)})})]})}function dh({isOpen:s,onClose:e,pairs:t,signals:i,isLoading:n,selectedSymbol:a,onSelect:o,onOpenAddModal:l}){const[c,d]=y.useState("");if(!s)return null;const h=new Map(i.map(v=>[v.symbol,v])),u=t.filter(v=>v.is_active).length,m=t.filter(v=>v.symbol.toLowerCase().includes(c.toLowerCase().trim())),x=[...m.filter(v=>v.is_active)].sort((v,p)=>v.symbol.localeCompare(p.symbol)),b=m.filter(v=>!v.is_active),f=v=>{o(v),e()};return r.jsxs("div",{className:"fixed inset-0 z-50 md:hidden flex",children:[r.jsx("div",{className:"fixed inset-0 bg-black/80 backdrop-blur-sm transition-opacity",onClick:e}),r.jsxs("div",{className:"relative w-4/5 max-w-xs h-full bg-bg-card border-r border-border shadow-2xl flex flex-col z-10 animate-fade-in",children:[r.jsxs("div",{className:"p-4 border-b border-border space-y-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ia,{size:16,className:"text-accent-blue"}),r.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Trading Pairs"}),u>0&&r.jsxs("span",{className:"text-[10px] font-mono bg-accent-blue/15 text-accent-blue border border-accent-blue/30 px-1.5 py-0.5 rounded font-semibold",children:[u," Aktif"]})]}),r.jsx("button",{onClick:e,className:"p-1 rounded-lg text-text-secondary hover:text-text-primary hover:bg-bg-elevated transition-colors",children:r.jsx(Ct,{size:18})})]}),a&&r.jsxs("button",{onClick:()=>f(null),className:"w-full flex items-center justify-center gap-1.5 py-1.5 px-3 rounded-lg bg-accent-blue/10 border border-accent-blue/30 text-xs font-semibold text-accent-blue hover:bg-accent-blue/20 transition-colors",children:[r.jsx(Xs,{size:13}),r.jsx("span",{children:"Tampilkan Semua Pair (Reset Filter)"})]}),r.jsxs("div",{className:"relative",children:[r.jsx(Zs,{size:14,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-text-muted pointer-events-none"}),r.jsx("input",{type:"text",placeholder:"Cari pair (e.g. BTC, ETH)...",value:c,onChange:v=>d(v.target.value),className:"input-field w-full pl-8 pr-3 py-1.5 text-xs font-mono"}),c&&r.jsx("button",{onClick:()=>d(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary",children:r.jsx(Ct,{size:12})})]}),r.jsx(se,{variant:"primary",size:"sm",onClick:()=>{e(),l()},icon:r.jsx(or,{size:14}),className:"w-full justify-center text-xs h-8",children:"Tambah Pair Baru"})]}),r.jsx("div",{className:"flex-1 overflow-y-auto py-2 custom-scrollbar",children:n?r.jsx("div",{className:"space-y-2 px-3",children:[...Array(5)].map((v,p)=>r.jsx("div",{className:"space-y-1.5 py-2",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Te,{className:"w-2 h-2 rounded-full"}),r.jsx(Te,{className:"h-4 flex-1"})]})},p))}):m.length===0?r.jsx("div",{className:"p-4 text-center",children:r.jsx("p",{className:"text-xs text-text-muted",children:c?`Tidak ada pair "${c}"`:"Belum ada pair ditambahkan"})}):r.jsxs("div",{className:"space-y-1 px-2",children:[x.map(v=>r.jsx(Hs,{pair:v,signal:h.get(v.symbol),isSelected:a===v.symbol,onSelect:p=>f(p)},v.id)),b.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 pt-3 pb-1",children:r.jsx("p",{className:"text-[10px] uppercase tracking-widest text-text-muted font-medium",children:"Nonaktif"})}),b.map(v=>r.jsx(Hs,{pair:v,signal:h.get(v.symbol),isSelected:a===v.symbol,onSelect:p=>f(p)},v.id))]})]})}),r.jsx("div",{className:"p-3 border-t border-border bg-bg-primary/50 shrink-0",children:r.jsx("div",{className:"grid grid-cols-3 gap-2 text-center",children:["LONG","SHORT","NEUTRAL"].map(v=>{const p=i.filter(g=>g.direction===v).length;return r.jsxs("div",{children:[r.jsx("p",{className:`text-xs font-bold font-mono ${v==="LONG"?"text-signal-long":v==="SHORT"?"text-signal-short":"text-text-muted"}`,children:p}),r.jsx("p",{className:"text-[9px] text-text-muted font-medium",children:v})]},v)})})})]})]})}function hh(s,e){return e==="LONG"?s>=7?"from-emerald-500 to-green-400":s>=4?"from-yellow-500 to-amber-400":"from-gray-500 to-gray-400":e==="SHORT"?s>=7?"from-red-500 to-rose-400":s>=4?"from-orange-500 to-amber-400":"from-gray-500 to-gray-400":"from-gray-500 to-gray-400"}function uh(s,e){return e==="LONG"?s>=7?"text-signal-long":s>=4?"text-accent-yellow":"text-text-secondary":e==="SHORT"?s>=7?"text-signal-short":s>=4?"text-orange-400":"text-text-secondary":"text-text-secondary"}function mh(s){return s>=8?"Very High":s>=6?"High":s>=4?"Moderate":s>=2?"Low":"Very Low"}function ph({score:s,direction:e,showLabel:t=!0}){const i=Math.max(0,Math.min(10,s)),n=i/10*100,a=hh(i,e),o=uh(i,e);return r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-xs text-text-secondary font-medium",children:"Conviction"}),r.jsxs("div",{className:"flex items-center gap-2",children:[t&&r.jsx("span",{className:"text-xs text-text-secondary",children:mh(i)}),r.jsx("span",{className:`font-mono font-bold text-lg leading-none ${o}`,children:i.toFixed(1)}),r.jsx("span",{className:"text-xs text-text-muted",children:"/10"})]})]}),r.jsxs("div",{className:"relative h-2 bg-bg-elevated rounded-full overflow-hidden border border-border",children:[r.jsx("div",{className:`absolute inset-y-0 left-0 rounded-full bg-gradient-to-r ${a} transition-all duration-700 ease-out`,style:{width:`${n}%`}}),[3,6,9].map(l=>r.jsx("div",{className:"absolute inset-y-0 w-px bg-bg-primary/50",style:{left:`${l/10*100}%`}},l))]}),r.jsxs("div",{className:"flex justify-between text-[10px] text-text-muted font-mono",children:[r.jsx("span",{children:"0"}),r.jsx("span",{children:"5"}),r.jsx("span",{children:"10"})]})]})}const fh=[{key:"funding_rate",icon:"📊",label:"Funding Rate",getValue:s=>{const e=s.funding_rate.value;return e==null||isNaN(e)?"N/A":`${e>=0?"+":""}${(e*100).toFixed(4)}%`},getScore:s=>s.funding_rate.score},{key:"oi_divergence",icon:"📈",label:"OI Divergence",getValue:s=>String(s.oi_divergence.value||"Neutral"),getScore:s=>s.oi_divergence.score},{key:"cvd",icon:"💹",label:"Futures CVD",getValue:s=>{const e=s.cvd.value;return typeof e=="number"?Math.abs(e)>=1e6?`${(e/1e6).toFixed(2)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1)}K`:e.toFixed(2):String(e)},getScore:s=>s.cvd.score},{key:"spot_futures_cvd",icon:"🏆",label:"Spot vs Fut CVD",getValue:s=>String(s.spot_futures_cvd?.value||"Futures Only"),getScore:s=>s.spot_futures_cvd?.score??0},{key:"hyperliquid",icon:"⚡",label:"Hyperliquid DEX",getValue:s=>String(s.hyperliquid?.value||"N/A"),getScore:s=>s.hyperliquid?.score??0},{key:"cross_exchange",icon:"🔀",label:"3-Way Consensus",getValue:s=>{const e=s.cross_exchange.divergence_pct;return e==null||isNaN(e)?"0.000%":`${e.toFixed(3)}%`},getScore:s=>s.cross_exchange.score},{key:"ls_ratio",icon:"👥",label:"L/S Ratio",getValue:s=>{const e=s.ls_ratio.top_trader;return e==null||isNaN(e)?"N/A":`${(e*100).toFixed(1)}% Long`},getScore:s=>s.ls_ratio.score},{key:"basis",icon:"📐",label:"Basis",getValue:s=>{const e=s.basis.value;if(e==null)return"N/A";const t=Number(e);return isNaN(t)?String(e):`${t>=0?"+":""}${t.toFixed(4)}%`},getScore:s=>s.basis.score},{key:"market_structure",icon:"🏗️",label:"Market Structure",getValue:s=>{const e=s.market_structure,t=e?.tf?String(e.tf).toUpperCase():"1H";return`${e?.structure||"Ranging"} (${t})`},getScore:s=>s.market_structure?.score??0},{key:"orderbook_skew",icon:"📚",label:"Orderbook Skew",getValue:s=>String(s.orderbook_skew?.value||s.orderbook_skew?.label||"Balanced"),getScore:s=>s.orderbook_skew?.score??0},{key:"whale_order_flow",icon:"🐋",label:"Whale Block Flow",getValue:s=>String(s.whale_order_flow?.value||s.whale_order_flow?.label||"Balanced"),getScore:s=>s.whale_order_flow?.score??0},{key:"fake_detector",icon:"⚠️",label:"Fake Detector",getValue:s=>{const e=s.fake_detector;return e&&e.warnings&&e.warnings.length>0?`${e.warnings.length} warning${e.warnings.length!==1?"s":""}`:"Clean"},getScore:s=>s.fake_detector?.score??0}];function xh({score:s}){return s>0?r.jsx("span",{className:"w-2 h-2 rounded-full bg-signal-long inline-block"}):s<0?r.jsx("span",{className:"w-2 h-2 rounded-full bg-signal-short inline-block"}):r.jsx("span",{className:"w-2 h-2 rounded-full bg-text-muted inline-block"})}function bh({score:s}){return s===0?r.jsx("span",{className:"font-mono text-xs text-text-muted",children:"[0]"}):s>0?r.jsxs("span",{className:"font-mono text-xs text-signal-long",children:["[+",s,"]"]}):r.jsxs("span",{className:"font-mono text-xs text-signal-short",children:["[",s,"]"]})}function gh({signals:s,predictive:e}){return r.jsxs("div",{className:"space-y-1",children:[fh.map(t=>{const i=t.getValue(s),n=t.getScore(s);return r.jsxs("div",{className:"flex items-center gap-3 py-2 px-3 rounded-lg hover:bg-bg-elevated transition-colors group",children:[r.jsx("span",{className:"text-sm w-5 shrink-0",children:t.icon}),r.jsx("span",{className:"text-[11px] sm:text-xs text-text-secondary w-24 sm:w-32 shrink-0 font-medium",children:t.label}),r.jsx("span",{className:"font-mono text-xs text-text-primary flex-1 min-w-0 break-words leading-tight",children:i}),r.jsx(bh,{score:n}),r.jsx(xh,{score:n})]},t.key)}),s.market_structure?.structure_per_tf&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-border",children:[r.jsx("p",{className:"text-[11px] font-semibold text-text-secondary uppercase tracking-wider mb-2",children:"Multi-Timeframe Structure (1D ➔ 5M)"}),r.jsx("div",{className:"grid grid-cols-5 gap-1.5 text-center font-mono",children:["1d","4h","1h","15m","5m"].map(t=>{const i=s.market_structure?.structure_per_tf?.[t]||"unknown",n=i==="bullish",a=i==="bearish",o=s.market_structure?.tf?.toLowerCase()===t;return r.jsxs("div",{className:`py-1.5 px-1 rounded-md border text-xs flex flex-col items-center justify-center ${o?"ring-1 ring-accent-blue font-bold":""} ${n?"bg-signal-long/10 border-signal-long/30 text-signal-long":a?"bg-signal-short/10 border-signal-short/30 text-signal-short":"bg-bg-elevated border-border text-text-muted"}`,children:[r.jsx("span",{className:"text-[10px] text-text-muted uppercase font-bold",children:t}),r.jsx("span",{className:"text-[10px] truncate max-w-full font-medium",children:n?"▲ BULL":a?"▼ BEAR":"━ CHOP"})]},t)})})]}),e&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-border",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("p",{className:"text-[11px] font-semibold text-accent-blue uppercase tracking-wider",children:"🔮 Forward Anticipation & Liquidity Pools"}),e.volatility_squeeze.is_squeeze&&r.jsx("span",{className:"text-[10px] font-mono text-amber-400 font-bold",children:"⚡ Squeeze Active"})]}),r.jsxs("div",{className:"space-y-2 text-xs",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{className:"p-2 rounded-lg bg-bg-elevated border border-border",children:[r.jsx("span",{className:"text-[9px] text-text-muted uppercase block font-medium",children:"Short Liq Pool (Upper Magnet)"}),r.jsxs("span",{className:"font-mono font-bold text-signal-short",children:[e.liquidation_magnets.upper_magnet_str," ",r.jsxs("span",{className:"text-[10px] font-normal text-text-secondary",children:["(+",e.liquidation_magnets.dist_upper_pct,"%)"]})]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-elevated border border-border",children:[r.jsx("span",{className:"text-[9px] text-text-muted uppercase block font-medium",children:"Long Liq Pool (Lower Magnet)"}),r.jsxs("span",{className:"font-mono font-bold text-signal-long",children:[e.liquidation_magnets.lower_magnet_str," ",r.jsxs("span",{className:"text-[10px] font-normal text-text-secondary",children:["(",e.liquidation_magnets.dist_lower_pct,"%)"]})]})]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-elevated/70 border border-border flex flex-col gap-1 text-[11px]",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("span",{className:"text-text-secondary",children:["Resting Depth Skew",e.orderbook_skew?.venues_count&&e.orderbook_skew.venues_count>1?` (${e.orderbook_skew.venues_count} Bursa)`:"",":"]}),r.jsx("span",{className:"font-mono font-semibold text-text-primary",children:e.orderbook_skew?.resting_pressure||"BALANCED RESTING DEPTH"})]}),e.orderbook_skew&&(e.orderbook_skew.bid_depth_usd>0||e.orderbook_skew.ask_depth_usd>0)&&r.jsxs("div",{className:"flex items-center justify-between text-[10px] font-mono pt-1 border-t border-border/40",children:[r.jsxs("span",{className:"text-emerald-400 font-medium",children:["Bids: ",e.orderbook_skew.bid_depth_usd>=1e6?`$${(e.orderbook_skew.bid_depth_usd/1e6).toFixed(2)}M`:e.orderbook_skew.bid_depth_usd>=1e3?`$${(e.orderbook_skew.bid_depth_usd/1e3).toFixed(1)}K`:`$${e.orderbook_skew.bid_depth_usd.toFixed(0)}`]}),r.jsx("span",{className:"text-text-muted",children:"vs"}),r.jsxs("span",{className:"text-rose-400 font-medium",children:["Asks: ",e.orderbook_skew.ask_depth_usd>=1e6?`$${(e.orderbook_skew.ask_depth_usd/1e6).toFixed(2)}M`:e.orderbook_skew.ask_depth_usd>=1e3?`$${(e.orderbook_skew.ask_depth_usd/1e3).toFixed(1)}K`:`$${e.orderbook_skew.ask_depth_usd.toFixed(0)}`]})]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-elevated/70 border border-border flex items-center justify-between text-[11px]",children:[r.jsx("span",{className:"text-text-secondary",children:"Volatility State:"}),r.jsx("span",{className:"font-mono font-semibold text-amber-400 truncate ml-2",children:e.volatility_squeeze?.label||"Kondisi Volatilitas Rata-Rata"})]})]})]}),s.fake_detector.is_fake&&s.fake_detector.warnings.length>0&&r.jsxs("div",{className:"mt-2 p-3 rounded-lg bg-signal-short-bg border border-signal-short/20",children:[r.jsx("p",{className:"text-xs text-signal-short font-semibold mb-1.5",children:"⚠️ Fake Signal Detected"}),r.jsx("ul",{className:"space-y-0.5",children:s.fake_detector.warnings.map((t,i)=>r.jsxs("li",{className:"text-xs text-text-secondary flex gap-1.5",children:[r.jsx("span",{className:"text-signal-short",children:"•"})," ",t]},i))})]})]})}function vh(s){return s==null||isNaN(s)?"N/A":s>=1e9?`$${(s/1e9).toFixed(2)}B`:s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${s.toLocaleString("en-US",{maximumFractionDigits:0})}`}function yh(s){return s==null||isNaN(s)?"N/A":`${s>=0?"+":""}${(s*100).toFixed(4)}%`}function wh(s){return s==null||isNaN(s)?"N/A":s>=1e3?`$${s.toLocaleString("en-US",{maximumFractionDigits:2})}`:s>=1?`$${s.toFixed(4)}`:`$${s.toFixed(6)}`}function qt({name:s,logo:e,funding_rate:t,oi:i,mark_price:n}){const a=t!=null?t<0?"text-signal-long":t>0?"text-signal-short":"text-text-secondary":"text-text-muted";return r.jsxs("div",{className:"flex items-center gap-3 py-2",children:[r.jsxs("div",{className:"flex items-center gap-2 w-20 shrink-0",children:[r.jsx("span",{className:"text-base",children:e}),r.jsx("span",{className:"text-xs font-semibold text-text-secondary",children:s})]}),r.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-1.5 sm:gap-2 min-w-0",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-[9px] sm:text-[10px] text-text-muted uppercase tracking-wide",children:"Funding"}),r.jsx("p",{className:`font-mono text-[11px] sm:text-xs font-semibold truncate ${a}`,children:yh(t)})]}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-[9px] sm:text-[10px] text-text-muted uppercase tracking-wide",children:"Open Int."}),r.jsx("p",{className:"font-mono text-[11px] sm:text-xs text-text-primary truncate",children:vh(i)})]}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-[9px] sm:text-[10px] text-text-muted uppercase tracking-wide",children:"Mark Price"}),r.jsx("p",{className:"font-mono text-[11px] sm:text-xs text-text-primary truncate",children:wh(n)})]})]})]})}function Nh({exchangeData:s}){return!!!(s&&(s.binance||s.bybit||s.okx||s.bitget||s.hyperliquid))||!s?r.jsx("div",{className:"py-3 text-center text-xs text-text-muted",children:"No exchange data available"}):r.jsxs("div",{className:"divide-y divide-border",children:[s.binance&&r.jsx(qt,{name:"Binance",logo:"🟡",...s.binance}),s.bybit&&r.jsx(qt,{name:"Bybit",logo:"🟠",...s.bybit}),s.okx&&r.jsx(qt,{name:"OKX",logo:"🔵",...s.okx}),s.bitget&&r.jsx(qt,{name:"Bitget",logo:"🟢",...s.bitget}),s.hyperliquid&&r.jsx(qt,{name:"Hyperliquid",logo:"⚡",...s.hyperliquid})]})}function jh(...s){return ps(ms(s))}const _h={long:"bg-signal-long-bg text-signal-long border border-signal-long/30",short:"bg-signal-short-bg text-signal-short border border-signal-short/30",neutral:"bg-signal-neutral-bg text-text-secondary border border-border",blue:"bg-blue-500/10 text-accent-blue border border-accent-blue/30",yellow:"bg-yellow-500/10 text-accent-yellow border border-accent-yellow/30"};function Sh({variant:s="neutral",size:e="sm",children:t,className:i}){return r.jsx("span",{className:jh("inline-flex items-center gap-1 font-mono font-semibold rounded-md",e==="sm"?"text-xs px-2 py-0.5":"text-sm px-2.5 py-1",_h[s],i),children:t})}const oi={getAll:async()=>{const{data:s}=await ie.get("/api/signals");return s},getBySymbol:async s=>{const{data:e}=await ie.get(`/api/signals/${s}/latest`);return e},getAccuracy:async(s=30,e)=>{const{data:t}=await ie.get("/api/signals/accuracy",{params:e?{days:s,symbol:e}:{days:s}});return t},refresh:async s=>{const{data:e}=await ie.post(`/api/signals/${s}/refresh`);return e},refreshAll:async()=>{const{data:s}=await ie.post("/api/signals/refresh-all");return s}},ct=["signals"];function li(){return Zt({queryKey:ct,queryFn:oi.getAll,placeholderData:s=>s,refetchInterval:Yi?3e4:6e3,refetchOnWindowFocus:!1,retry:2,staleTime:Yi?15e3:4e3})}function Va(){const s=os();return as({mutationFn:e=>oi.refresh(e),onSuccess:e=>{s.setQueryData([...ct,e.symbol],e),s.invalidateQueries({queryKey:ct})}})}function kh(){const s=os();return as({mutationFn:()=>oi.refreshAll(),onSuccess:e=>{e?.signals&&s.setQueryData(ct,e.signals),s.invalidateQueries({queryKey:ct})}})}const Mh=y.lazy(()=>pt(()=>import("./AIAnalysisPanel-BbXTq8TV.js"),__vite__mapDeps([4,1,2,3])).then(s=>({default:s.AIAnalysisPanel})));function Ch(s){const e=Date.now(),t=new Date(s).getTime(),i=e-t,n=Math.floor(i/1e3);if(n<60)return`${n}s ago`;const a=Math.floor(n/60);return a<60?`${a}m ago`:`${Math.floor(a/60)}h ago`}function vs(s){return!s||isNaN(s)||s<=0?"$0":s>=1e6?`$${(s/1e6).toFixed(2)}M`:s>=1e3?`$${(s/1e3).toFixed(1)}K`:`$${s.toFixed(0)}`}const Eh={LONG:"glow-long border-signal-long/20",SHORT:"glow-short border-signal-short/20",NEUTRAL:"border-border"},rn={LONG:"animate-pulse-green",SHORT:"animate-pulse-red"};function Th({signal:s,onNavigateToAI:e,onNavigateToChart:t}){const[i,n]=y.useState(!1),[a,o]=y.useState(!1),[l,c]=y.useState(!1),[d,h]=y.useState(!1),[u,m]=y.useState(()=>!s.veto_reason&&s.horizons?.intraday?.direction==="NEUTRAL"&&s.horizons?.swing?.direction&&s.horizons.swing.direction!=="NEUTRAL"?"swing":"intraday"),{mutate:x,isPending:b}=Va(),{toast:f}=ft();y.useEffect(()=>{h(!0);const z=setTimeout(()=>h(!1),900);return()=>clearTimeout(z)},[s.updated_at]),y.useEffect(()=>{const z=s.horizons?.intraday?.direction,V=s.horizons?.swing?.direction;!s.veto_reason&&z==="NEUTRAL"&&V&&V!=="NEUTRAL"?m("swing"):(s.veto_reason||z&&z!=="NEUTRAL")&&m("intraday")},[s.veto_reason,s.horizons?.intraday?.direction,s.horizons?.swing?.direction]);const v=()=>{x(s.symbol,{onSuccess:()=>f(`${s.symbol} refreshed`,"success"),onError:z=>f(z.message,"error")})},p=s.horizons?s.horizons[u]:void 0,g=p?.direction??s.direction,S=p?.conviction??s.conviction,j=p?.action||s.action,k=p?.quick_verdict||s.quick_verdict,C=p?p.trade_levels:s.trade_levels,M=C?.squeeze_intensity==="EXTREME SQUEEZE"||C?.squeeze_intensity==="MODERATE SQUEEZE",L=s.predictive?.orderbook_skew,I=L?.bid_depth_usd??0,R=L?.ask_depth_usd??0,T=I+R,E=T>0?Math.round(I/T*100):50,F=T>0?100-E:50,B=z=>{z.stopPropagation();const V=g==="LONG",q=`⚡ PERPS AI: ${s.symbol} ${g} (${p?.timeframe||s.active_timeframe}) -Action: ${j||(V?"BUY":"SELL")} -Conviction: ${S}/10 -${C?`Entry Zone: ${C.entry_zone} -Stop Loss: ${C.stop_loss_str} -Take Profit 1: ${C.take_profit_1_str} -Take Profit 2: ${C.take_profit_2_str} -🎯 Magnet Target: ${C.predicted_target||"N/A"} -R:R: ${C.risk_reward}`:""} -Verdict: ${k||""} -Forward Anticipation: ${s.anticipation||C?.anticipation||""}`;navigator.clipboard.writeText(q),o(!0),f(`${s.symbol} plan copied!`,"success"),setTimeout(()=>o(!1),2e3)};return r.jsxs("div",{className:`card border transition-all duration-300 flex flex-col justify-between signal-card-container overflow-hidden rounded-xl ${d?"ring-1 ring-accent-blue/50":""} ${s.has_spot===!1?"border-amber-500/30 hover:border-amber-500/50":"border-border hover:border-border/80"} ${Eh[s.direction]}`,children:[r.jsxs("div",{className:"p-3.5 sm:p-4 flex flex-col flex-1 justify-between",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:`w-2.5 h-2.5 rounded-full shrink-0 ${s.direction==="LONG"?"bg-signal-long "+rn.LONG:s.direction==="SHORT"?"bg-signal-short "+rn.SHORT:"bg-text-muted"}`}),r.jsx("h3",{className:"text-sm sm:text-base font-bold font-mono text-text-primary leading-none truncate",children:s.symbol})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[s.streak&&s.streak>=2&&r.jsxs("span",{className:"text-[10px] font-mono font-bold px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-400 border border-amber-500/30 flex items-center gap-0.5 shrink-0 animate-pulse",title:`Consistent Conviction Streak: ${s.streak} cycles`,children:["🔥 ",s.streak,"x"]}),r.jsx(dr,{direction:s.direction,size:"sm"}),r.jsxs("span",{className:`text-[10px] font-mono font-bold px-1.5 py-0.5 rounded border ${s.conviction>=6?"bg-signal-long/15 text-signal-long border-signal-long/30":s.conviction>=3?"bg-accent-blue/15 text-accent-blue border-accent-blue/30":"bg-bg-elevated text-text-muted border-border"}`,title:`Conviction: ${s.conviction}/10`,children:[s.conviction,"/10"]})]})]}),r.jsxs("div",{className:"flex items-center justify-between gap-2 mb-3 text-[11px] text-text-secondary",children:[r.jsx("span",{className:"truncate capitalize",children:s.market_condition||"Normal Market"}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 flex-wrap justify-end",children:[s.sniper_grade==="SNIPER_A_PLUS"&&r.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 flex items-center gap-1",title:"Sniper A+: Intraday (15m-4H) & Swing (4H-1D) searah + Spot/Squeeze terkonfirmasi",children:[r.jsx(Ye,{size:10,className:"text-emerald-400"}),r.jsx("span",{children:"SNIPER A+"})]}),s.sniper_grade==="INTRADAY_ONLY"&&r.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-cyan-500/15 text-cyan-300 border border-cyan-500/35 flex items-center gap-1",title:"Intraday Setup (15m-4H)",children:r.jsx("span",{children:"⚡ INTRADAY"})}),s.sniper_grade==="SWING_SETUP"&&r.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-indigo-500/15 text-indigo-300 border border-indigo-500/35 flex items-center gap-1",title:"Swing Setup (4H-1D)",children:r.jsx("span",{children:"🌊 SWING"})}),s.sniper_grade==="SNIPER_COUNTER"&&r.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/40 flex items-center gap-1",title:"Counter-Trend: Intraday berlawanan dengan struktur Swing 4H-1D",children:r.jsx("span",{children:"⚠️ COUNTER"})}),s.liquidity_guard&&!s.liquidity_guard.passed&&r.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-rose-500/20 text-rose-300 border border-rose-500/40 flex items-center gap-1",title:`Spread ${s.liquidity_guard.spread_bps} bps | Depth ±1.5%: $${s.liquidity_guard.depth_usd.toLocaleString()}`,children:r.jsx("span",{children:"Thin Book"})}),s.has_spot===!1&&r.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-amber-500/15 text-amber-300 border border-amber-500/30 flex items-center gap-1",title:"Aset RAWAN BANDAR: Kontrak Perp-Only tanpa pasar Spot riil.",children:[r.jsx(ve,{size:10,className:"text-amber-400"}),r.jsx("span",{children:"Perp Only"})]}),s.has_spot===!0&&r.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/25 flex items-center gap-1",title:"Aset AMAN: Pasar Spot riil tersedia.",children:[r.jsx(Et,{size:10,className:"text-emerald-400"}),r.jsx("span",{children:"Spot"})]}),s.breakout_radar?.is_breakout_primed?r.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono font-bold border flex items-center gap-1 ${s.breakout_radar.squeeze_stage==="READY_TO_BURST"?"bg-purple-500/25 text-purple-300 border-purple-500/50 animate-pulse":"bg-amber-500/20 text-amber-300 border-amber-500/40"}`,title:s.breakout_radar.catalyst_summary,children:[r.jsx(Ae,{size:10,className:"text-yellow-400"}),r.jsx("span",{children:s.breakout_radar.squeeze_stage==="READY_TO_BURST"?"BURST PRIMED":"COILING"})]}):M?r.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-amber-500/20 text-amber-400 border border-amber-500/30 flex items-center gap-1 animate-pulse",title:"Volatility Squeeze (Breakout Imminent)",children:[r.jsx(Ae,{size:10}),r.jsx("span",{children:"Squeeze"})]}):null,r.jsx(Sh,{variant:"blue",size:"sm",children:s.active_timeframe})]})]}),(s.quick_verdict||s.anticipation||s.has_spot===!1)&&r.jsxs("div",{className:`mb-3 p-2.5 rounded-lg border text-xs space-y-1.5 transition-colors ${s.has_spot===!1?"bg-amber-950/20 border-amber-500/30":"bg-bg-elevated/70 border-border/80"}`,children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("span",{className:`font-mono font-bold uppercase text-[9px] sm:text-[10px] px-1.5 py-0.5 rounded shrink-0 tracking-wide ${g==="LONG"?"bg-signal-long/20 text-signal-long border border-signal-long/30":g==="SHORT"?"bg-signal-short/20 text-signal-short border border-signal-short/30":s.breakout_radar?.is_breakout_primed?"bg-purple-500/25 text-purple-300 border border-purple-500/40 animate-pulse":"bg-bg-elevated text-text-muted border border-border"}`,children:j||(g==="LONG"?"BUY":g==="SHORT"?"SELL":"WAIT")}),r.jsx("p",{className:"text-[11px] sm:text-xs text-text-primary font-medium flex-1 leading-snug",children:k||(g==="LONG"?"Akumulasi beli dengan momentum tinggi":g==="SHORT"?"Tekanan jual terkonfirmasi":"Struktur pasar sideways/chop. Disarankan Wait-and-See.")})]}),s.anticipation&&s.anticipation!==s.quick_verdict&&r.jsxs("div",{className:"flex items-start gap-1.5 text-[10px] sm:text-[11px] text-accent-blue/90 pt-1 border-t border-border/40",children:[r.jsx("span",{className:"font-semibold shrink-0 uppercase font-mono tracking-wider text-[9px]",children:"🔮 Antisipasi:"}),r.jsx("span",{className:"text-text-secondary leading-snug",children:s.anticipation})]}),s.has_spot===!1&&r.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-amber-300/90 pt-1 border-t border-amber-500/20 font-medium",children:[r.jsx(ve,{size:11,className:"shrink-0 text-amber-400"}),r.jsx("span",{children:"Koin Perp-Only (tanpa spot). Wajib pasang SL ketat!"})]})]}),r.jsx(ph,{score:S,direction:g}),r.jsx("div",{className:"mt-2.5 p-2 rounded-lg bg-bg-elevated/40 border border-border/60",children:T>0?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-between text-[10px] font-mono mb-1",children:[r.jsxs("span",{className:"text-emerald-400 font-semibold flex items-center gap-1",children:[r.jsx("span",{children:"Bids"}),r.jsx("span",{className:"text-text-primary font-bold",children:vs(I)}),r.jsxs("span",{className:"text-text-muted text-[9px]",children:["(",E,"%)"]})]}),r.jsx("span",{className:"text-[9px] uppercase tracking-wider text-text-muted font-sans font-medium",title:L?.venues_count&&L.venues_count>1?`Likuiditas teragregasi dari ${L.venues_count} bursa (±1.5%)`:"Kedalaman orderbook ±1.5%",children:L?.venues_count&&L.venues_count>1?`Global Depth (${L.venues_count} Bursa)`:"Depth ±1.5%"}),r.jsxs("span",{className:"text-rose-400 font-semibold flex items-center gap-1",children:[r.jsxs("span",{className:"text-text-muted text-[9px]",children:["(",F,"%)"]}),r.jsx("span",{className:"text-text-primary font-bold",children:vs(R)}),r.jsx("span",{children:"Asks"})]})]}),r.jsxs("div",{className:"h-2 w-full bg-bg-card rounded-full overflow-hidden flex shadow-inner border border-border/30",children:[r.jsx("div",{className:"bg-emerald-500 h-full transition-all duration-500 rounded-l-full",style:{width:`${E}%`},title:`Bids (Beli): ${vs(I)} (${E}%)`}),r.jsx("div",{className:"bg-rose-500 h-full transition-all duration-500 rounded-r-full",style:{width:`${F}%`},title:`Asks (Jual): ${vs(R)} (${F}%)`})]}),r.jsxs("div",{className:"flex items-center justify-between mt-1 text-[9px] font-mono text-text-muted",children:[r.jsx("span",{className:E>=58?"text-emerald-400 font-bold":"",children:E>=65?"🛡️ Bid Wall Dominant":E>=55?"Buyers Ahead":"Buyers"}),r.jsx("span",{className:"text-text-secondary text-[9px]",children:L?.skew_ratio!==void 0?Math.abs(L.skew_ratio)<.05?"Skew: Balanced":`Skew: ${L.skew_ratio>0?"+":""}${(L.skew_ratio*100).toFixed(0)}%`:""}),r.jsx("span",{className:F>=58?"text-rose-400 font-bold":"",children:F>=65?"🛑 Ask Wall Dominant":F>=55?"Sellers Ahead":"Sellers"})]})]}):r.jsxs("div",{className:"flex items-center justify-between text-[10px] font-mono text-text-muted py-0.5",children:[r.jsxs("span",{className:"flex items-center gap-1.5 text-[9px] text-text-secondary",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"}),r.jsx("span",{children:"Order Book Depth:"}),r.jsx("span",{className:"text-text-muted italic",children:"Sinkronisasi antrean bursa..."})]}),r.jsx("span",{className:"text-[9px] text-accent-blue/80 font-sans",children:"Live Sync"})]})}),s.horizons&&r.jsx("div",{className:"mt-2.5 flex items-center justify-between gap-1.5 p-1 rounded-lg bg-bg-elevated/60 border border-border/60 text-[10px] font-mono",children:["intraday","swing"].map(z=>{const V=s.horizons?.[z];if(!V)return null;const q=u===z,J=V.direction==="LONG"?"text-signal-long":V.direction==="SHORT"?"text-signal-short":"text-text-muted";return r.jsxs("button",{type:"button",onClick:()=>m(z),className:`flex-1 py-1 px-2 rounded-md flex items-center justify-between transition-all ${q?"bg-bg-card text-text-primary border border-border shadow-sm font-bold":"text-text-muted hover:text-text-secondary"}`,children:[r.jsx("span",{children:z==="intraday"?"⚡ 15m-4H":"🌊 4H-1D"}),r.jsxs("span",{className:J,children:[V.direction," (",V.conviction,"/10)"]})]},z)})}),C&&r.jsxs("div",{className:`mt-3 p-2.5 rounded-lg border flex flex-col gap-2 ${s.has_spot===!1?"bg-amber-950/15 border-amber-500/25":"bg-bg-primary/80 border-border/70"}`,children:[r.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono border-b border-border/40 pb-1.5 gap-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[r.jsx("span",{className:"text-[9px] uppercase font-bold tracking-wider text-text-muted shrink-0",children:"ENTRY:"}),r.jsx("span",{className:"font-bold text-text-primary text-[11px] whitespace-normal",children:C.entry_zone})]}),r.jsxs("button",{onClick:B,title:"Copy Trade Plan",className:"px-2 py-0.5 rounded-md hover:bg-bg-elevated border border-border/60 hover:border-border text-text-muted hover:text-text-primary transition-all shrink-0 flex items-center gap-1 text-[10px] font-mono active:scale-95",children:[a?r.jsx(rt,{size:11,className:"text-signal-long"}):r.jsx(es,{size:11}),r.jsx("span",{children:a?"Copied":"Plan"})]})]}),r.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 font-mono text-[10px] sm:text-[11px]",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-[8px] sm:text-[9px] uppercase tracking-wider text-signal-short block font-semibold",children:"SL"}),r.jsx("span",{className:"font-bold text-signal-short block whitespace-nowrap",children:C.stop_loss_str})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-[8px] sm:text-[9px] uppercase tracking-wider text-signal-long block font-semibold",children:"TP1"}),r.jsx("span",{className:"font-bold text-signal-long block whitespace-nowrap",children:C.take_profit_1_str})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-[8px] sm:text-[9px] uppercase tracking-wider text-signal-long/80 block font-semibold",children:"TP2"}),r.jsx("span",{className:"font-bold text-signal-long/90 block whitespace-nowrap",children:C.take_profit_2_str||"—"})]}),C.predicted_target?r.jsxs("div",{children:[r.jsxs("span",{className:"text-[8px] sm:text-[9px] uppercase tracking-wider text-amber-400 flex items-center gap-0.5 font-semibold",children:[r.jsx(Ye,{size:9})," Magnet"]}),r.jsx("span",{className:"font-bold text-amber-300 block whitespace-nowrap",children:C.predicted_target})]}):r.jsxs("div",{children:[r.jsx("span",{className:"text-[8px] sm:text-[9px] uppercase tracking-wider text-text-muted block font-semibold",children:"R:R"}),r.jsx("span",{className:"font-bold text-text-secondary block whitespace-nowrap",children:C.risk_reward})]})]})]})]}),r.jsxs("div",{className:"flex items-center justify-between gap-2 mt-3 pt-2.5 border-t border-border/40",children:[r.jsxs("div",{className:"flex items-center gap-1 text-[10px] sm:text-[11px] text-text-muted",children:[r.jsx(Fs,{size:11}),r.jsx("span",{children:Ch(s.updated_at)})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[t&&r.jsxs("button",{onClick:()=>t(s.symbol),className:"px-2.5 py-1 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition-all shadow-sm active:scale-95 cursor-pointer border bg-sky-500/15 hover:bg-sky-500/25 border-sky-500/40 hover:border-sky-400 text-sky-300 hover:text-white",title:"Buka Live Chart & Order Flow Real-Time",children:[r.jsx(nt,{size:11,className:"text-sky-400"}),r.jsx("span",{children:"Chart"})]}),r.jsxs("button",{onClick:()=>{e?e(s.symbol):c(z=>!z)},className:"px-2.5 py-1 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition-all shadow-sm active:scale-95 cursor-pointer border bg-gradient-to-r from-purple-500/20 to-blue-500/20 hover:from-purple-500/30 hover:to-blue-500/30 border-purple-500/40 hover:border-purple-400 text-purple-300 hover:text-white",title:"Buka Halaman Tanya AI Khusus untuk Pair Ini",children:[r.jsx(Fe,{size:11,className:"text-purple-400 animate-pulse"}),r.jsx("span",{children:"Tanya AI"})]}),r.jsx(se,{variant:"ghost",size:"sm",onClick:v,loading:b,icon:r.jsx(Re,{size:11}),className:"text-xs px-2 py-1 h-7",children:r.jsx("span",{className:"hidden xs:inline",children:"Refresh"})}),r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>n(z=>!z),icon:i?r.jsx(Us,{size:11}):r.jsx(jt,{size:11}),className:"text-xs px-2 py-1 h-7",children:i?"Hide":"Details"})]})]})]}),i&&r.jsxs("div",{className:"border-t border-border animate-fade-in",children:[r.jsxs("div",{className:"p-5",children:[r.jsx("p",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wider mb-3",children:"Signal Breakdown (Kalkulasi Otomatis Sistem)"}),r.jsx(gh,{signals:s.signals,predictive:s.predictive})]}),r.jsxs("div",{className:"border-t border-border px-5 py-4",children:[r.jsx("p",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wider mb-3",children:"Exchange Data"}),r.jsx(Nh,{exchangeData:s.exchange_data})]})]}),l&&r.jsxs("div",{className:"border-t border-purple-500/30 bg-bg-card/95 p-4 rounded-b-xl space-y-3 animate-fade-in",children:[r.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-border/60",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"p-1 rounded bg-purple-500/20 text-purple-400",children:r.jsx(Be,{size:14})}),r.jsxs("span",{className:"text-xs font-bold text-purple-300",children:["Hasil Analisa Murni AI (",s.symbol,")"]})]}),r.jsx("span",{className:"text-[10px] text-text-muted italic",children:"*Terpisah dari kalkulasi otomatis sistem"})]}),r.jsx(y.Suspense,{fallback:r.jsxs("div",{className:"py-6 flex items-center justify-center gap-2 text-xs text-text-muted",children:[r.jsx(Re,{size:14,className:"animate-spin text-purple-400"}),r.jsx("span",{children:"Memuat modul AI..."})]}),children:r.jsx(Mh,{symbol:s.symbol})})]})]})}const Rh=y.memo(Th,(s,e)=>s.signal.symbol===e.signal.symbol&&s.signal.updated_at===e.signal.updated_at&&s.signal.conviction===e.signal.conviction&&s.signal.direction===e.signal.direction&&s.signal.score===e.signal.score&&s.signal.sniper_grade===e.signal.sniper_grade&&s.signal.veto_reason===e.signal.veto_reason&&s.signal.liquidity_guard?.status===e.signal.liquidity_guard?.status&&s.signal.horizons?.intraday?.score===e.signal.horizons?.intraday?.score&&s.signal.horizons?.intraday?.direction===e.signal.horizons?.intraday?.direction&&s.signal.horizons?.swing?.score===e.signal.horizons?.swing?.score&&s.signal.horizons?.swing?.direction===e.signal.horizons?.swing?.direction&&s.signal.quick_verdict===e.signal.quick_verdict&&s.signal.action===e.signal.action&&s.signal.has_spot===e.signal.has_spot&&s.signal.predictive?.orderbook_skew?.bid_depth_usd===e.signal.predictive?.orderbook_skew?.bid_depth_usd&&s.signal.predictive?.orderbook_skew?.ask_depth_usd===e.signal.predictive?.orderbook_skew?.ask_depth_usd&&s.onNavigateToAI===e.onNavigateToAI&&s.onNavigateToChart===e.onNavigateToChart);function Ph({topSignal:s}){const[e,t]=y.useState(!1),[i,n]=y.useState(null),{toast:a}=ft();if(y.useEffect(()=>{let h=!0;const u=()=>{oi.getAccuracy(30).then(x=>{h&&n(x)}).catch(()=>{})};u();const m=setInterval(u,6e4);return()=>{h=!1,clearInterval(m)}},[]),!s||s.direction==="NEUTRAL"||s.conviction<3)return r.jsx("div",{className:"mb-6 p-4 rounded-xl border border-border bg-card/60 backdrop-blur flex items-center justify-between gap-4",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-10 h-10 rounded-xl bg-bg-elevated border border-border flex items-center justify-center shrink-0 text-text-muted",children:r.jsx(Oo,{size:20})}),r.jsxs("div",{children:[r.jsxs("h3",{className:"text-sm font-semibold text-text-primary flex items-center gap-2",children:["Capital Preservation Mode",r.jsx("span",{className:"text-[10px] font-mono px-2 py-0.5 rounded-full bg-bg-elevated text-text-muted border border-border",children:"No Trades ≥ 3/10"})]}),r.jsx("p",{className:"text-xs text-text-secondary mt-0.5",children:s?.anticipation||"Pasar sedang konsolidasi / chop. Sistem melindungi saldo Anda dari jebakan whipsaw. Tunggu hingga muncul peluang akumulasi institusi."})]})]})});const o=s.direction==="LONG",l=s.trade_levels,c=l?.squeeze_intensity==="EXTREME SQUEEZE"||l?.squeeze_intensity==="MODERATE SQUEEZE",d=()=>{const h=`⚡ PERPS AI FORWARD TRADE SETUP -Pair: ${s.symbol} -Direction: ${s.direction} (Conviction ${s.conviction}/10) -Action: ${s.action||(o?"BUY":"SELL")} -${l?`Entry Zone: ${l.entry_zone} -Stop Loss: ${l.stop_loss_str} -Take Profit 1: ${l.take_profit_1_str} -Take Profit 2: ${l.take_profit_2_str} -🎯 Magnet Target: ${l.predicted_target||"N/A"} (${l.target_type||"Liquidity Pool"}) -R:R: ${l.risk_reward}`:""} -Verdict: ${s.quick_verdict||""} -Forward Anticipation: ${s.anticipation||l?.anticipation||""}`;navigator.clipboard.writeText(h),t(!0),a("Forward trade setup copied to clipboard!","success"),setTimeout(()=>t(!1),2500)};return r.jsx("div",{className:`mb-5 sm:mb-6 p-3.5 sm:p-5 rounded-2xl border transition-all duration-300 relative overflow-hidden ${o?"bg-gradient-to-r from-signal-long/10 via-card to-card border-signal-long/30 shadow-[0_0_25px_rgba(16,185,129,0.12)]":"bg-gradient-to-r from-signal-short/10 via-card to-card border-signal-short/30 shadow-[0_0_25px_rgba(239,68,68,0.12)]"}`,children:r.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-4",children:[r.jsxs("div",{className:"space-y-2 max-w-xl",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsxs("span",{className:`px-2.5 py-1 rounded-lg text-xs font-bold uppercase tracking-wider flex items-center gap-1.5 ${o?"bg-signal-long text-bg-primary font-mono":"bg-signal-short text-white font-mono"}`,children:[r.jsx(ts,{size:13,className:"animate-bounce"}),"TOP SETUP: ",s.symbol]}),r.jsx("span",{className:`font-mono text-xs font-bold px-2 py-0.5 rounded-md border ${o?"bg-signal-long/20 text-signal-long border-signal-long/40":"bg-signal-short/20 text-signal-short border-signal-short/40"}`,children:s.direction}),r.jsxs("span",{className:"font-mono text-xs font-bold text-text-primary px-2 py-0.5 rounded-md bg-bg-elevated border border-border",children:[s.conviction,"/10"]}),s.sniper_grade==="SNIPER_A_PLUS"&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 flex items-center gap-1",children:[r.jsx(Ye,{size:11,className:"text-emerald-400"}),"SNIPER A+"]}),i&&i.total_evaluated>0&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-bold bg-cyan-500/15 text-cyan-300 border border-cyan-500/35 flex items-center gap-1",title:`30d Forward Accuracy (${i.total_evaluated} evaluated | TP Hit Rate: ${i.tp_hit_rate_pct}% | Avg R: ${i.avg_r_multiple>=0?"+":""}${i.avg_r_multiple}R)`,children:["🎯 30d Win Rate:"," ",i.sniper_a_plus.total>0?`${i.sniper_a_plus.win_rate_pct}% (Sniper A+)`:`${i.win_rate_pct}% (${i.total_evaluated})`]}),s.streak&&s.streak>=2&&r.jsxs("span",{className:"font-mono text-xs font-bold px-2 py-0.5 rounded-md bg-amber-500/20 text-amber-300 border border-amber-500/40 flex items-center gap-1 animate-pulse",title:`Consistent Conviction Streak: ${s.streak} cycles`,children:["🔥 ",s.streak,"x Streak"]}),r.jsx("span",{className:"text-[11px] font-mono text-text-secondary uppercase px-1.5 py-0.5 rounded bg-bg-elevated border border-border",children:s.active_timeframe}),s.has_spot===!0&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-medium bg-emerald-500/15 text-emerald-400 border border-emerald-500/30 flex items-center gap-1",children:[r.jsx(Et,{size:11,className:"text-emerald-400"}),"Spot OK"]}),s.has_spot===!1&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/40 flex items-center gap-1",children:[r.jsx(ve,{size:11,className:"text-amber-400"}),"Perp Only"]}),c&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-bold bg-amber-500/20 text-amber-400 border border-amber-500/30 flex items-center gap-1 animate-pulse",children:[r.jsx(Ae,{size:11}),"Squeeze"]})]}),r.jsx("p",{className:"text-xs sm:text-sm font-medium text-text-primary leading-snug",children:s.quick_verdict||(o?"Peluang akumulasi beli dengan momentum tinggi.":"Peluang tekanan jual agresif terkonfirmasi.")}),s.anticipation&&r.jsxs("div",{className:"flex items-start gap-1.5 text-xs text-accent-blue bg-accent-blue/10 border border-accent-blue/20 px-2.5 py-1.5 rounded-lg",children:[r.jsx("span",{className:"font-semibold shrink-0 text-[11px] font-mono",children:"🔮 Antisipasi:"}),r.jsx("span",{className:"text-text-primary text-[11px] leading-relaxed",children:s.anticipation})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 text-xs text-text-muted pt-0.5",children:[r.jsxs("span",{className:"flex items-center gap-1 text-[11px]",children:[r.jsx(Et,{size:12,className:"text-accent-blue"}),"Consensus Validated"]}),l?.predicted_target&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"hidden sm:inline text-border",children:"•"}),r.jsxs("span",{className:"flex items-center gap-1 text-text-primary font-mono text-[11px]",children:[r.jsx(Ye,{size:12,className:"text-amber-400"}),"Target Magnet: ",r.jsx("span",{className:"text-amber-300 font-bold",children:l.predicted_target})]})]}),s.has_spot===!1&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"hidden sm:inline text-border",children:"•"}),r.jsxs("span",{className:"flex items-center gap-1 text-amber-400 text-[11px] font-medium",children:[r.jsx(ve,{size:12}),"Perp-Only (Disiplin Stop Loss!)"]})]})]})]}),l?r.jsx("div",{className:"bg-bg-primary/90 border border-border/80 p-3 sm:p-3.5 rounded-xl backdrop-blur shrink-0",children:r.jsxs("div",{className:"grid grid-cols-2 sm:flex sm:items-center gap-2 sm:gap-3",children:[r.jsxs("div",{className:"space-y-0.5 pr-2 sm:border-r sm:border-border col-span-2 sm:col-span-1 bg-bg-elevated/40 sm:bg-transparent p-2 sm:p-0 rounded-lg",children:[r.jsx("p",{className:"text-[9px] uppercase tracking-wider text-text-muted font-medium",children:"Entry Zone"}),r.jsx("p",{className:"font-mono text-xs font-bold text-text-primary",children:l.entry_zone})]}),r.jsxs("div",{className:"space-y-0.5 px-0 sm:px-2 sm:border-r sm:border-border bg-bg-elevated/40 sm:bg-transparent p-2 sm:p-0 rounded-lg",children:[r.jsx("p",{className:"text-[9px] uppercase tracking-wider text-signal-short font-medium",children:"Stop Loss"}),r.jsx("p",{className:"font-mono text-xs font-bold text-signal-short",children:l.stop_loss_str})]}),r.jsxs("div",{className:"space-y-0.5 px-0 sm:px-2 sm:border-r sm:border-border bg-bg-elevated/40 sm:bg-transparent p-2 sm:p-0 rounded-lg",children:[r.jsx("p",{className:"text-[9px] uppercase tracking-wider text-signal-long font-medium",children:"TP1 / TP2"}),r.jsxs("p",{className:"font-mono text-xs font-bold text-signal-long",children:[l.take_profit_1_str," / ",l.take_profit_2_str]})]}),l.predicted_target&&r.jsxs("div",{className:"space-y-0.5 px-0 sm:px-2 sm:border-r sm:border-border bg-bg-elevated/40 sm:bg-transparent p-2 sm:p-0 rounded-lg col-span-2 sm:col-span-1",children:[r.jsx("p",{className:"text-[9px] uppercase tracking-wider text-amber-400 font-medium",children:"Magnet Target"}),r.jsx("p",{className:"font-mono text-xs font-bold text-amber-300",children:l.predicted_target})]}),r.jsxs("button",{onClick:d,className:"col-span-2 sm:col-span-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg bg-bg-elevated hover:bg-border border border-border text-xs font-semibold text-text-primary transition-all active:scale-95",title:"Copy Trade Signal to Clipboard",children:[e?r.jsx(rt,{size:14,className:"text-signal-long"}):r.jsx(es,{size:14}),r.jsx("span",{children:e?"Copied!":"Copy Plan"})]})]})}):r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("button",{onClick:d,className:"w-full sm:w-auto flex items-center justify-center gap-1.5 px-3.5 py-2 rounded-lg bg-bg-elevated hover:bg-border border border-border text-xs font-semibold text-text-primary transition-all",children:[e?r.jsx(rt,{size:14,className:"text-signal-long"}):r.jsx(es,{size:14}),r.jsx("span",{children:e?"Copied":"Copy Signal"})]})})]})})}const Lh=y.memo(Ph,(s,e)=>s.topSignal?.symbol===e.topSignal?.symbol&&s.topSignal?.updated_at===e.topSignal?.updated_at&&s.topSignal?.conviction===e.topSignal?.conviction&&s.topSignal?.direction===e.topSignal?.direction&&s.topSignal?.sniper_grade===e.topSignal?.sniper_grade&&s.topSignal?.veto_reason===e.topSignal?.veto_reason&&s.topSignal?.quick_verdict===e.topSignal?.quick_verdict&&s.topSignal?.has_spot===e.topSignal?.has_spot&&s.topSignal?.anticipation===e.topSignal?.anticipation),Ah=y.lazy(()=>pt(()=>import("./AddPairModal-D8YkLLF_.js"),__vite__mapDeps([0,1,2,3])).then(s=>({default:s.AddPairModal})));function Oh({onNavigateToAI:s,onNavigateToChart:e,isMobileDrawerOpen:t,setIsMobileDrawerOpen:i}){const[n,a]=y.useState(null),[o,l]=y.useState("ALL"),[c,d]=y.useState("STABLE"),[h,u]=y.useState(!1),{data:m=[],isLoading:x,error:b}=us(),{data:f=[],isLoading:v}=li(),{mutate:p,isPending:g}=Va(),{mutate:S,isPending:j}=kh(),k=b?.status,C=k===401||k===503,M=y.useMemo(()=>{const $=new Set(m.filter(N=>N.is_active).map(N=>N.symbol));return[...f.filter(N=>$.has(N.symbol))].sort((N,U)=>U.conviction!==N.conviction?U.conviction-N.conviction:N.symbol.localeCompare(U.symbol))},[f,m]),L=y.useMemo(()=>M.find($=>$.direction!=="NEUTRAL"&&$.conviction>=3),[M]),I=y.useMemo(()=>{if(n)return f.filter(W=>W.symbol===n);const $=M.filter(W=>o==="SPOT_ONLY"?W.has_spot===!0:o==="PERP_ONLY"?W.has_spot===!1:o==="HOT"?W.conviction>=4:o==="LONG"?W.direction==="LONG":o==="SHORT"?W.direction==="SHORT":!0);return c==="STABLE"?[...$].sort((W,N)=>W.symbol.localeCompare(N.symbol)):$},[n,M,o,c,f]);y.useEffect(()=>{if(n&&!g){const $=f.find(N=>N.symbol===n);(!$||!$.updated_at||Date.now()-new Date($.updated_at).getTime()>18e4)&&p(n)}},[n,f,g,p]),y.useEffect(()=>{if(f.length===0||j)return;const $=()=>{const N=Date.now();f.filter(A=>{const ee=A.updated_at?new Date(A.updated_at).getTime():0;return!ee||N-ee>18e4}).length>5&&!j&&S()};$();const W=setInterval($,6e4);return()=>clearInterval(W)},[f,j,S]);const R=m.filter($=>$.is_active),T=(x||v)&&m.length===0&&f.length===0,E=!T&&R.length===0,F=n!==null&&I.length===0,B=!T&&!n&&R.length>0&&M.length===0,z=y.useMemo(()=>M.filter($=>$.has_spot===!0).length,[M]),V=y.useMemo(()=>M.filter($=>$.has_spot===!1).length,[M]),q=y.useMemo(()=>M.filter($=>$.conviction>=4).length,[M]),J=y.useMemo(()=>M.filter($=>$.direction==="LONG").length,[M]),oe=y.useMemo(()=>M.filter($=>$.direction==="SHORT").length,[M]);return r.jsxs("div",{className:"flex flex-1 h-full overflow-hidden bg-bg-primary",children:[r.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[r.jsx("div",{className:"hidden md:flex",children:r.jsx(ch,{pairs:m,signals:f,isLoading:x,selectedSymbol:n,onSelect:$=>a(W=>W===$?null:$)})}),r.jsx(dh,{isOpen:t,onClose:()=>i(!1),pairs:m,signals:f,isLoading:x,selectedSymbol:n,onSelect:$=>a($),onOpenAddModal:()=>u(!0)}),r.jsxs("main",{className:"flex-1 overflow-y-auto p-3 sm:p-5 custom-scrollbar pb-20 md:pb-5",children:[C&&r.jsxs("div",{className:"mb-4 p-3.5 rounded-xl bg-amber-500/10 border border-amber-500/35 text-xs text-amber-200 flex items-start gap-2.5",children:[r.jsx(ve,{size:16,className:"text-amber-400 shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("p",{className:"font-semibold",children:k===503?"Backend Memerlukan PERPS_API_TOKEN":"API Bearer Token Belum Terpasang / Tidak Cocok"}),r.jsx("p",{className:"text-[11px] text-amber-200/80 mt-0.5",children:b?.message||"Klik indikator status koneksi di pojok kanan atas Header untuk mengisi PERPS_API_TOKEN agar Watchlist Pair & Jurnal aktif."})]})]}),!n&&M.length>0&&r.jsx(Lh,{topSignal:L}),n&&r.jsxs("div",{className:"mb-4 flex items-center justify-between gap-2 p-2.5 sm:p-3 rounded-xl bg-accent-blue/10 border border-accent-blue/30 text-xs animate-fade-in",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"font-mono font-bold text-text-primary text-sm sm:text-base truncate",children:n}),r.jsx("span",{className:"text-[10px] sm:text-[11px] text-accent-blue font-semibold uppercase px-1.5 py-0.5 rounded bg-accent-blue/15 border border-accent-blue/30 shrink-0",children:"Fokus Pair"})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>p(n),loading:g,icon:r.jsx(Re,{size:12,className:g?"animate-spin":""}),className:"text-xs h-8 px-2 sm:px-3",children:r.jsx("span",{className:"hidden xs:inline",children:"Refresh"})}),r.jsx(se,{variant:"primary",size:"sm",onClick:()=>a(null),icon:r.jsx(zo,{size:13}),className:"text-xs h-8 px-2.5 sm:px-3.5 shadow-sm",children:"Semua Pair"})]})]}),!n&&r.jsxs("div",{className:"flex flex-col gap-3 mb-4 sm:mb-5",children:[r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-base sm:text-lg font-bold text-text-primary leading-tight",children:"Market Conviction Overview"}),r.jsxs("p",{className:"text-[11px] sm:text-xs text-text-secondary mt-0.5",children:["Menampilkan ",I.length," dari ",M.length," pair aktif"]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 shrink-0",children:[r.jsxs("button",{type:"button",onClick:()=>S(),disabled:j,className:"px-2.5 py-1.5 rounded-lg text-xs font-medium border border-border bg-bg-elevated hover:bg-bg-card text-text-secondary hover:text-text-primary flex items-center gap-1.5 transition-all shadow-sm shrink-0 active:scale-95 disabled:opacity-60",title:"Perbarui seluruh data sinyal pasar sekarang",children:[r.jsx(Re,{size:12,className:j?"animate-spin text-accent-blue":""}),r.jsx("span",{className:"hidden xs:inline",children:j?"Memperbarui...":"Refresh Pasar"})]}),r.jsxs("button",{type:"button",onClick:()=>d($=>$==="STABLE"?"CONVICTION":"STABLE"),className:"px-2.5 py-1.5 rounded-lg text-xs font-medium border border-border bg-bg-elevated hover:bg-bg-card text-text-secondary hover:text-text-primary flex items-center gap-1.5 transition-all shadow-sm shrink-0",title:c==="STABLE"?"Posisi kartu stabil (A-Z, kartu tidak loncat-loncat)":"Diurutkan berdasarkan skor keyakinan tertinggi",children:[r.jsx("span",{className:"text-[10px] text-text-muted hidden xs:inline",children:"Tata Letak:"}),r.jsx("span",{className:"font-semibold text-text-primary",children:c==="STABLE"?"📌 A-Z":"🔥 Skor"})]})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 p-1 rounded-xl bg-bg-elevated/70 border border-border/80 overflow-x-auto no-scrollbar",children:[r.jsxs("button",{onClick:()=>l("ALL"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all shrink-0 ${o==="ALL"?"bg-card text-text-primary shadow-sm font-semibold":"text-text-secondary hover:text-text-primary"}`,children:[r.jsx(Xs,{size:13}),r.jsxs("span",{children:["All (",M.length,")"]})]}),r.jsxs("button",{onClick:()=>l("SPOT_ONLY"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all shrink-0 ${o==="SPOT_ONLY"?"bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 font-semibold":"text-text-secondary hover:text-emerald-400"}`,title:"Hanya pair yang memiliki pasar Spot riil (Aman dari manipulasi bandar perp-only)",children:[r.jsx(Et,{size:13,className:"text-emerald-400"}),r.jsxs("span",{children:["🛡️ Aman (",z,")"]})]}),r.jsxs("button",{onClick:()=>l("PERP_ONLY"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all shrink-0 ${o==="PERP_ONLY"?"bg-amber-500/20 text-amber-300 border border-amber-500/40 font-semibold":"text-text-secondary hover:text-amber-400"}`,title:"Hanya pair PERP-ONLY tanpa pasar Spot (Rawan manipulasi bandar)",children:[r.jsx(ve,{size:13,className:"text-amber-400"}),r.jsxs("span",{children:["⚠️ Rawan (",V,")"]})]}),r.jsxs("button",{onClick:()=>l("HOT"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all shrink-0 ${o==="HOT"?"bg-amber-500/20 text-amber-400 border border-amber-500/30 font-semibold":"text-text-secondary hover:text-amber-400"}`,children:[r.jsx(ts,{size:13,className:q>0?"text-amber-400":""}),r.jsxs("span",{children:["Ready ≥4 (",q,")"]})]}),r.jsxs("button",{onClick:()=>l("LONG"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all shrink-0 ${o==="LONG"?"bg-signal-long/20 text-signal-long border border-signal-long/30 font-semibold":"text-text-secondary hover:text-signal-long"}`,children:[r.jsx(ra,{size:13}),r.jsxs("span",{children:["Longs (",J,")"]})]}),r.jsxs("button",{onClick:()=>l("SHORT"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all shrink-0 ${o==="SHORT"?"bg-signal-short/20 text-signal-short border border-signal-short/30 font-semibold":"text-text-secondary hover:text-signal-short"}`,children:[r.jsx(na,{size:13}),r.jsxs("span",{children:["Shorts (",oe,")"]})]})]})]}),T&&r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3 sm:gap-4",children:[...Array(3)].map(($,W)=>r.jsx(ih,{},W))}),E&&r.jsxs("div",{className:"flex flex-col items-center justify-center h-[55vh] text-center space-y-4 p-4",children:[r.jsx("div",{className:"w-14 h-14 rounded-2xl bg-accent-blue/10 border border-accent-blue/20 flex items-center justify-center",children:r.jsx(Qe,{size:26,className:"text-accent-blue"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Belum Ada Trading Pair"}),r.jsx("p",{className:"text-xs text-text-secondary mt-1 max-w-xs",children:"Tambahkan trading pair pertama Anda untuk mulai menganalisa sinyal perpetual futures."})]}),r.jsx(se,{variant:"primary",size:"md",onClick:()=>u(!0),icon:r.jsx(or,{size:15}),children:"Tambah Pair Pertama"})]}),F&&r.jsxs("div",{className:"flex flex-col items-center justify-center h-[45vh] text-center space-y-4 animate-fade-in p-4",children:[r.jsx("div",{className:"w-14 h-14 rounded-2xl bg-accent-blue/10 border border-accent-blue/20 flex items-center justify-center",children:r.jsx(sn,{size:"md"})}),r.jsxs("div",{children:[r.jsxs("h3",{className:"text-sm font-semibold text-text-primary",children:["Menganalisa ",n,"..."]}),r.jsx("p",{className:"text-xs text-text-secondary mt-1 max-w-xs",children:"Mengalkulasi CVD, Open Interest, Funding Rate, dan Market Structure dari Binance, Bybit, OKX, dan Hyperliquid."})]})]}),B&&r.jsxs("div",{className:"flex flex-col items-center justify-center h-[40vh] text-center space-y-4 p-4",children:[r.jsx("div",{className:"w-12 h-12 rounded-2xl bg-bg-elevated border border-border flex items-center justify-center",children:r.jsx(sn,{size:"md"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Memuat Sinyal Pasar"}),r.jsx("p",{className:"text-xs text-text-secondary mt-1 max-w-xs",children:"Mengambil data live bursa dan konsensus multi-exchange..."})]})]}),!T&&I.length===0&&M.length>0&&!n&&r.jsxs("div",{className:"flex flex-col items-center justify-center h-[35vh] text-center space-y-3 p-5 sm:p-6 rounded-2xl border border-border bg-card",children:[r.jsx("div",{className:"w-12 h-12 rounded-xl bg-bg-elevated border border-border flex items-center justify-center text-text-muted",children:r.jsx(ts,{size:20})}),r.jsxs("h3",{className:"text-sm font-semibold text-text-primary",children:['Tidak Ada Pair yang Memenuhi Filter "',o,'"']}),r.jsx("p",{className:"text-xs text-text-secondary max-w-md",children:o==="HOT"?"Saat ini belum ada coin dengan conviction ≥ 4/10. Jangan fomo atau paksakan entry. Bersantai dulu sampai setup institusi yang valid muncul!":`Tidak ada sinyal aktif dengan arah ${o}.`}),r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>l("ALL"),children:"Reset ke Semua Pair"})]}),!T&&I.length>0&&r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3 sm:gap-4",children:I.map($=>r.jsx(Rh,{signal:$,onNavigateToAI:s,onNavigateToChart:e},$.symbol))})]})]}),h&&r.jsx(y.Suspense,{fallback:null,children:r.jsx(Ah,{isOpen:h,onClose:()=>u(!1)})})]})}const zh=[{id:"anthropic/claude-fable-5",label:"Claude Fable 5 (Vikey Default)",category:"Anthropic"},{id:"anthropic/claude-fable-5.1",label:"Claude Fable 5.1",category:"Anthropic"},{id:"anthropic/claude-sonnet-5.5",label:"Claude Sonnet 5.5",category:"Anthropic"},{id:"anthropic/claude-sonnet-5",label:"Claude Sonnet 5",category:"Anthropic"},{id:"anthropic/claude-opus-5.5",label:"Claude Opus 5.5",category:"Anthropic"},{id:"anthropic/haiku-5.5",label:"Claude Haiku 5.5 (Fast)",category:"Anthropic"},{id:"deepseek/deepseek-v4-pro",label:"DeepSeek V4 Pro",category:"DeepSeek"},{id:"deepseek/deepseek-v4-flash",label:"DeepSeek V4 Flash",category:"DeepSeek"},{id:"deepseek/deepseek-v4.1-flash",label:"DeepSeek V4.1 Flash",category:"DeepSeek"},{id:"openai/gpt-5.6-sol",label:"GPT-5.6 Sol",category:"OpenAI"},{id:"openai/gpt-6-astra",label:"GPT-6 Astra",category:"OpenAI"},{id:"openai/gpt-5.6-luna",label:"GPT-5.6 Luna",category:"OpenAI"},{id:"openai/gpt-6.1-sol",label:"GPT-6.1 Sol",category:"OpenAI"},{id:"gemini/gemini-3.8-flash",label:"Gemini 3.8 Flash",category:"Google"},{id:"gemini/gemini-3.7-flash-high",label:"Gemini 3.7 Flash High",category:"Google"},{id:"qwen/qwen3.8-max",label:"Qwen 3.8 Max",category:"Qwen"},{id:"vikey/qwen3.8-27b-uncensored",label:"Qwen 3.8 27B Uncensored",category:"Qwen"},{id:"moonshot/kimi-k3",label:"Moonshot Kimi K3",category:"Moonshot"},{id:"minimax/minimax-m3",label:"MiniMax M3",category:"MiniMax"},{id:"zai/glm-5.3",label:"ZAI GLM 5.3",category:"GLM"}],Ih=[{id:"gemini-2.5-flash",label:"Gemini 2.5 Flash (Recommended)"},{id:"gemini-1.5-flash",label:"Gemini 1.5 Flash"},{id:"gemini-2.0-flash",label:"Gemini 2.0 Flash"},{id:"gemini-1.5-pro",label:"Gemini 1.5 Pro"}],$h=[{id:"gpt-4o-mini",label:"GPT-4o Mini (Fast)"},{id:"gpt-4o",label:"GPT-4o"},{id:"o3-mini",label:"o3-mini"}],ki="perps_ai_settings_changed";function Mi(){const s=localStorage.getItem("perps_ai_provider")||"vikey",e=localStorage.getItem("perps_ai_api_key")||"";let t=localStorage.getItem("perps_ai_model")||"";t||(s==="vikey"?t="anthropic/claude-fable-5":s==="gemini"?t="gemini-2.5-flash":t="gpt-4o-mini");const i=localStorage.getItem("perps_ai_base_url")||"",n=localStorage.getItem("perps_ai_max_tokens"),a=n?parseInt(n,10):void 0;return{provider:s,api_key:e,model:t,base_url:i,max_tokens:a}}function ci(){const[s,e]=y.useState(Mi),t=y.useCallback(()=>{e(Mi())},[]);y.useEffect(()=>(window.addEventListener(ki,t),window.addEventListener("storage",t),()=>{window.removeEventListener(ki,t),window.removeEventListener("storage",t)}),[t]);const i=a=>{const l={...Mi(),...a};a.provider!==void 0&&localStorage.setItem("perps_ai_provider",l.provider),a.api_key!==void 0&&localStorage.setItem("perps_ai_api_key",l.api_key.trim()),a.model!==void 0&&localStorage.setItem("perps_ai_model",l.model.trim()),a.base_url!==void 0&&localStorage.setItem("perps_ai_base_url",l.base_url?.trim()||""),a.max_tokens!==void 0&&(a.max_tokens?localStorage.setItem("perps_ai_max_tokens",String(a.max_tokens)):localStorage.removeItem("perps_ai_max_tokens")),e(l),window.dispatchEvent(new Event(ki))},n=!!(s.api_key&&s.api_key.trim());return{settings:s,isConfigured:n,updateSettings:i,reloadSettings:t}}const Dh={analyze:async s=>{const{data:e}=await ie.post("/api/ai/analyze",s,{timeout:0});return e}},Le={logTrade:async s=>{const{data:e}=await ie.post("/api/journal/log",s);return e},getEntries:async(s="ALL",e=50,t=0)=>{const{data:i}=await ie.get("/api/journal",{params:{status:s,limit:e,offset:t}});return i},updateStatus:async(s,e,t,i,n,a)=>{const{data:o}=await ie.patch(`/api/journal/${s}/status`,{status:e,note:t,failure_tag:i,exit_price:n,holding_duration_seconds:a});return o},deleteEntry:async s=>{const{data:e}=await ie.delete(`/api/journal/${s}`);return e},getStats:async()=>{const{data:s}=await ie.get("/api/journal/stats");return s},getMemory:async()=>{const{data:s}=await ie.get("/api/journal/memory");return s},synthesizeAudit:async s=>{const{data:e}=await ie.post("/api/journal/audit",s);return e}};function Bh(...s){return ps(ms(s))}const Fh={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl"};function Is({isOpen:s,onClose:e,title:t,children:i,size:n="md"}){const a=y.useCallback(o=>{o.key==="Escape"&&e()},[e]);return y.useEffect(()=>(s&&(document.addEventListener("keydown",a),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",a),document.body.style.overflow=""}),[s,a]),s?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4",children:[r.jsx("div",{className:"absolute inset-0 bg-black/80 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:Bh("relative w-full max-h-[92vh] flex flex-col card shadow-2xl animate-fade-in my-auto",Fh[n]),onClick:o=>o.stopPropagation(),children:[r.jsxs("div",{className:"shrink-0 flex items-center justify-between px-4 sm:px-6 py-3.5 sm:py-4 border-b border-border",children:[r.jsx("h2",{className:"text-sm sm:text-base font-semibold text-text-primary truncate",children:t}),r.jsx("button",{onClick:e,className:"p-1.5 rounded-lg text-text-secondary hover:text-text-primary hover:bg-bg-elevated transition-colors ml-2 shrink-0",children:r.jsx(Ct,{size:16})})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-4 sm:px-6 py-4 sm:py-5 custom-scrollbar",children:i})]})]}):null}const vr="perps_bybit_session_creds";function Vs(){if(typeof window>"u")return null;try{const s=window.sessionStorage.getItem(vr);if(!s)return null;const e=JSON.parse(s);if(e?.api_key&&e?.api_secret)return{api_key:String(e.api_key).trim(),api_secret:String(e.api_secret).trim(),mode:e.mode||"demo"}}catch{}return null}function Uh(s){typeof window>"u"||window.sessionStorage.setItem(vr,JSON.stringify({api_key:s.api_key.trim(),api_secret:s.api_secret.trim(),mode:s.mode}))}function qh(){typeof window>"u"||window.sessionStorage.removeItem(vr)}function ys(s){const e=Vs();return e?{"X-Bybit-Api-Key":e.api_key,"X-Bybit-Api-Secret":e.api_secret,"X-Bybit-Mode":s||e.mode}:s?{"X-Bybit-Mode":s}:{}}const ws={getSettings:async()=>{const{data:s}=await ie.get("/api/execution/bybit/settings",{headers:ys()});return s},saveSettings:async s=>{const e=s.mode||"demo",{data:t}=await ie.post("/api/execution/bybit/settings",s,{headers:ys(e)});return t.success&&s.api_key&&s.api_secret&&Uh({api_key:s.api_key,api_secret:s.api_secret,mode:e}),t},getBalance:async s=>{const{data:e}=await ie.get("/api/execution/bybit/balance",{params:s?{mode:s}:{},headers:ys(s)});return e},executeOrder:async s=>{const e=Vs(),t={...s,api_key:s.api_key||e?.api_key,api_secret:s.api_secret||e?.api_secret,mode:s.mode||e?.mode},{data:i}=await ie.post("/api/execution/bybit/order",t,{headers:ys(t.mode)});return i}};function He(s){if(!s)return null;const e=s.match(/\$\s*([0-9]+(?:,[0-9]{3})*(?:\.[0-9]+)?|[0-9]+(?:\.[0-9]+)?)/);if(e&&e[1]){const n=parseFloat(e[1].replace(/,/g,""));if(!isNaN(n)&&n>0)return n}const i=s.replace(/\b(TP[12]|1[Hh]|4[Hh]|15[Mm]|5[Mm]|24[Hh]|1[Dd])\b[:\s-]*/gi,"").match(/([0-9]+(?:\.[0-9]+)?)/);if(i&&i[1]){const n=parseFloat(i[1]);if(!isNaN(n)&&n>0)return n}return null}function nn(s){if(!s)return 3;const e=s.match(/([0-9]+)\s*x/i);if(e&&e[1]){const t=parseInt(e[1],10);if(!isNaN(t)&&t>0)return Math.min(Math.max(t,1),50)}return 3}function Ka({isOpen:s,onClose:e,symbol:t,summary:i,markPrice:n,onExecutionSuccess:a}){const{toast:o}=ft(),l=i.bias.toUpperCase().includes("SHORT")||i.bias.toUpperCase().includes("SELL"),c=l?"Sell":"Buy",d=He(i.entryZone)||n||0,h=He(i.stopLoss)||(l?d*1.03:d*.97),u=He(i.takeProfit1)||(l?d*.95:d*1.05),m=He(i.takeProfit2),x=nn(i.leverage),[b,f]=y.useState("Limit"),[v,p]=y.useState("percent"),[g,S]=y.useState(5),[j,k]=y.useState(50),[C,M]=y.useState(x),[L,I]=y.useState(d),[R,T]=y.useState(h),[E,F]=y.useState(u),[B,z]=y.useState(m),[V,q]=y.useState(50),[J,oe]=y.useState(!0),[$,W]=y.useState(null),[N,U]=y.useState(null),[A,ee]=y.useState(!1),[xe,K]=y.useState(""),[te,be]=y.useState(""),[Se,Ze]=y.useState("demo"),[ge,we]=y.useState(!1),[_,Q]=y.useState(!1),[Y,Z]=y.useState(null);y.useEffect(()=>{const D=He(i.entryZone)||n||0,xt=He(i.stopLoss)||(l?D*1.03:D*.97),Mo=He(i.takeProfit1)||(l?D*.95:D*1.05),Co=He(i.takeProfit2),Eo=nn(i.leverage);I(D),T(xt),F(Mo),z(Co),M(Eo)},[t,l,i.entryZone,i.stopLoss,i.takeProfit1,i.takeProfit2,i.leverage,n]),y.useEffect(()=>{if(s){const D=Vs();D&&Ze(D.mode),H()}},[s]);const H=async()=>{Z(null);try{const D=await ws.getSettings();W(D),Ze(D.mode||"demo"),D.configured?(ee(!1),ke(D.mode)):ee(!0)}catch(D){const xt=D?.status;xt===401||xt===503?(Z(D?.message||"API Bearer Token belum diset / tidak cocok. Buka ikon status server di header untuk mengisi PERPS_API_TOKEN."),ee(!1)):ee(!0)}},X=()=>{qh(),K(""),be(""),U(null),o("Kredensial Bybit sesi browser telah dihapus dari memori lokal.","success"),H()},ke=async D=>{try{const xt=await ws.getBalance(D);U(xt)}catch{}},Oe=async()=>{if(!xe.trim()||!te.trim()){o("Masukkan API Key dan API Secret Bybit Anda.","error");return}we(!0);try{const D=await ws.saveSettings({api_key:xe.trim(),api_secret:te.trim(),mode:Se});o(D.message,"success"),W({configured:!0,masked_key:`${xe.slice(0,4)}***`,mode:Se}),D.balance&&U(D.balance),ee(!1)}catch(D){o(D.message||"Kredensial Bybit gagal divalidasi.","error")}finally{we(!1)}},Ce=N?.total_equity&&N.total_equity>0?N.total_equity:N?.available_balance&&N.available_balance>0?N.available_balance:0,xs=Ce>0?Math.max(1,Math.round(Ce*(g/100)*100)/100):0,ze=v==="percent"&&Ce>0?xs:j,ae=b==="Limit"&&L>0?L:n||L||1,bs=ze*C,bi=ae>0?(l?(R-ae)/ae:(ae-R)/ae)*bs:0,wo=V/100,No=(100-V)/100,jo=ae>0&&E>0?(l?(ae-E)/ae:(E-ae)/ae)*(bs*wo):0,_o=ae>0&&B&&B>0&&V<100?(l?(ae-B)/ae:(B-ae)/ae)*(bs*No):0,Tr=jo+_o,So=bi>0?(Tr/bi).toFixed(2):"N/A",ko=async()=>{if(!$?.configured){ee(!0),o("Harap masukkan API Key Bybit sebelum eksekusi.","info");return}if(v==="percent"){if(Ce<=0){o('Total equity Bybit terdeteksi $0 atau API belum terhubung. Silakan beralih ke tab "$ USD Tetap" atau hubungkan API Bybit.',"error");return}if(g<=0||g>100){o("Persentase alokasi equity harus antara 0.1% hingga 100%.","error");return}}else if(j<=0){o("Masukkan margin yang valid (> $0).","error");return}if(ze<=0){o("Margin efektif tidak valid atau $0.","error");return}if(R<=0||E<=0){o("Stop Loss dan Target TP1 wajib diisi.","error");return}if(c==="Buy"){if(R>=ae){o(`Stop Loss ($${R}) harus lebih rendah dari Entry ($${ae}) untuk posisi Long.`,"error");return}if(E<=ae){o(`Target TP1 ($${E}) harus lebih tinggi dari Entry ($${ae}) untuk posisi Long.`,"error");return}if(B&&V<100&&B<=E){o(`Target TP2 ($${B}) harus lebih tinggi dari TP1 ($${E}).`,"error");return}}else{if(R<=ae){o(`Stop Loss ($${R}) harus lebih tinggi dari Entry ($${ae}) untuk posisi Short.`,"error");return}if(E>=ae){o(`Target TP1 ($${E}) harus lebih rendah dari Entry ($${ae}) untuk posisi Short.`,"error");return}if(B&&V<100&&B>=E){o(`Target TP2 ($${B}) harus lebih rendah dari TP1 ($${E}).`,"error");return}}Q(!0);try{const D=await ws.executeOrder({symbol:t,side:c,order_type:b,margin_usd:ze,margin_percent:v==="percent"?g:null,leverage:C,stop_loss:R,take_profit_1:E,take_profit_2:V<100?B:null,tp1_percent:V,auto_breakeven:V<100&&B?J:!1,entry_price:b==="Limit"?L:void 0,mark_price:n,summary_tldr:i.verdictSummary});o(`🚀 ${D.message}`,"success"),a&&a(D),e()}catch(D){o(D.message||"Eksekusi order gagal.","error")}finally{Q(!1)}};return r.jsx(Is,{isOpen:s,onClose:e,title:`Eksekusi Order — ${t}`,size:"lg",children:r.jsxs("div",{className:"space-y-4 text-xs",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 p-3 rounded-xl bg-bg-elevated/60 border border-border",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:`px-2.5 py-1 rounded-lg text-xs font-bold font-mono flex items-center gap-1.5 border ${l?"bg-rose-500/20 text-rose-300 border-rose-500/40":"bg-emerald-500/20 text-emerald-300 border-emerald-500/40"}`,children:[l?r.jsx(Mt,{size:14}):r.jsx(Qe,{size:14}),r.jsxs("span",{children:[c.toUpperCase()," (",i.bias,")"]})]}),r.jsxs("span",{className:"text-[11px] text-text-muted font-mono hidden sm:inline",children:["Mark: $",n?.toLocaleString(void 0,{minimumFractionDigits:4})||"N/A"]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[$?.configured?r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-emerald-500/10 border border-emerald-500/30 text-[11px] text-emerald-300 font-mono",children:[r.jsx(sa,{size:12,className:"text-emerald-400"}),r.jsxs("span",{className:"font-semibold uppercase",children:[$.mode," Bybit"]}),N&&r.jsxs("span",{className:"text-emerald-400 font-bold ml-1",children:["$",(N.total_equity||N.available_balance).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})," USDT"]})]}):r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-amber-500/15 border border-amber-500/30 text-[11px] text-amber-300 font-mono",children:[r.jsx(ve,{size:12,className:"text-amber-400"}),r.jsx("span",{children:"API Belum Terpasang"})]}),r.jsx("button",{type:"button",onClick:()=>ee(!A),className:"p-1.5 rounded-lg bg-bg-card hover:bg-bg-elevated border border-border text-text-muted hover:text-text-primary transition-colors",title:"Konfigurasi API Key Bybit",children:r.jsx(Io,{size:13})})]})]}),Y&&r.jsxs("div",{className:"p-3 rounded-xl bg-rose-500/15 border border-rose-500/40 text-rose-200 flex items-start gap-2.5 text-xs",children:[r.jsx(ve,{size:15,className:"text-rose-400 shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("p",{className:"font-semibold",children:"Autentikasi Server Dibutuhkan"}),r.jsx("p",{className:"text-[11px] text-rose-200/80 mt-0.5",children:Y})]})]}),A&&r.jsxs("div",{className:"p-3.5 rounded-xl bg-purple-950/30 border border-purple-500/40 space-y-3 animate-fade-in",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[r.jsxs("span",{className:"text-xs font-bold text-purple-200 flex items-center gap-1.5",children:[r.jsx($o,{size:14,className:"text-purple-400"}),"Kredensial API Bybit (Stateless Per-Sesi)"]}),r.jsxs("span",{className:"text-[10px] text-purple-300/80 flex items-center gap-1",children:[r.jsx(Do,{size:10})," Disimpan hanya di sessionStorage & dikirim per-request"]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2.5",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-[10px] uppercase font-bold text-text-muted block mb-1",children:"Bybit API Key"}),r.jsx("input",{type:"text",value:xe,onChange:D=>K(D.target.value),placeholder:"Masukkan API Key Bybit",className:"w-full px-2.5 py-1.5 rounded-lg bg-bg-card border border-border text-xs text-text-primary font-mono focus:border-purple-500 focus:outline-none"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-[10px] uppercase font-bold text-text-muted block mb-1",children:"Bybit API Secret"}),r.jsx("input",{type:"password",value:te,onChange:D=>be(D.target.value),placeholder:"Masukkan API Secret Bybit",className:"w-full px-2.5 py-1.5 rounded-lg bg-bg-card border border-border text-xs text-text-primary font-mono focus:border-purple-500 focus:outline-none"})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-[10px] font-bold text-text-muted uppercase",children:"Lingkungan:"}),r.jsx("div",{className:"flex items-center gap-1",children:[{id:"demo",label:"Bybit Demo (api-demo)"},{id:"testnet",label:"Testnet"},{id:"real",label:"Live Real"}].map(D=>r.jsx("button",{type:"button",onClick:()=>Ze(D.id),className:`px-2 py-1 rounded text-[10px] font-mono font-semibold transition-all ${Se===D.id?"bg-purple-600 text-white shadow-sm":"bg-bg-card text-text-secondary hover:text-text-primary border border-border"}`,children:D.label},D.id))})]}),r.jsxs("div",{className:"flex items-center gap-1.5",children:[Vs()&&r.jsx(se,{variant:"ghost",size:"sm",onClick:X,icon:r.jsx(Qt,{size:12}),className:"text-rose-300 hover:text-rose-200",children:"Hapus Key Sesi"}),$?.configured&&r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>ee(!1),children:"Batal"}),r.jsx(se,{variant:"primary",size:"sm",onClick:Oe,loading:ge,className:"bg-purple-600 hover:bg-purple-500 text-white",children:"Simpan & Hubungkan"})]})]})]}),r.jsxs("div",{className:"p-3.5 rounded-xl bg-bg-elevated/40 border border-border space-y-3",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:"text-[11px] font-bold uppercase tracking-wider text-text-secondary flex items-center gap-1.5",children:[r.jsx(Bo,{size:13,className:"text-purple-400"}),"Alokasi Modal Margin"]}),r.jsxs("div",{className:"flex items-center rounded-lg border border-border bg-bg-card p-0.5",children:[r.jsx("button",{type:"button",onClick:()=>p("percent"),className:`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${v==="percent"?"bg-purple-600 text-white shadow-sm":"text-text-muted hover:text-text-primary"}`,children:"% Equity"}),r.jsx("button",{type:"button",onClick:()=>p("usd"),className:`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${v==="usd"?"bg-purple-600 text-white shadow-sm":"text-text-muted hover:text-text-primary"}`,children:"$ USD"})]})]}),r.jsxs("span",{className:"text-[11px] font-mono font-bold text-purple-300",children:["Notional Posisi: $",bs.toLocaleString(void 0,{minimumFractionDigits:1,maximumFractionDigits:1})," USD"]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsx("div",{className:"space-y-1.5",children:v==="percent"?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",min:"0.5",max:"100",step:"0.5",value:g,onChange:D=>S(Math.max(.1,parseFloat(D.target.value)||0)),className:"w-full pl-3 pr-8 py-1.5 rounded-lg bg-bg-card border border-border text-sm font-bold font-mono text-text-primary focus:border-purple-500 focus:outline-none"}),r.jsx("span",{className:"absolute right-3 top-2 text-text-muted font-mono text-xs font-bold",children:"%"})]}),r.jsx("div",{className:"flex items-center gap-1",children:[1,2,5,10,20].map(D=>r.jsxs("button",{type:"button",onClick:()=>S(D),className:`px-2 py-1.5 rounded-lg text-[10px] font-mono font-semibold border transition-all ${g===D?"bg-purple-600/30 border-purple-500 text-purple-200":"bg-bg-card border-border text-text-muted hover:text-text-primary"}`,children:[D,"%"]},D))})]}),r.jsx("div",{className:"text-[10.5px] font-mono",children:Ce>0?r.jsxs("span",{className:"text-purple-300",children:["⚡ ",r.jsxs("strong",{children:[g,"%"]})," = ",r.jsxs("strong",{className:"text-emerald-400",children:["$",xs.toFixed(2)," USD"]})," (dari equity $",Ce.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2}),")"]}):r.jsxs("span",{className:"text-amber-400/90 flex items-center gap-1",children:[r.jsx(ve,{size:11}),' Saldo equity $0 / belum terhubung. Silakan gunakan tab "$ USD".']})})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-2 text-text-muted font-mono text-xs",children:"$"}),r.jsx("input",{type:"number",min:"5",max:"50000",step:"5",value:j,onChange:D=>k(Math.max(1,parseFloat(D.target.value)||0)),className:"w-full pl-7 pr-3 py-1.5 rounded-lg bg-bg-card border border-border text-sm font-bold font-mono text-text-primary focus:border-purple-500 focus:outline-none"})]}),r.jsx("div",{className:"flex items-center gap-1",children:[25,50,100,200].map(D=>r.jsxs("button",{type:"button",onClick:()=>k(D),className:`px-2 py-1.5 rounded-lg text-[10px] font-mono font-semibold border transition-all ${j===D?"bg-purple-600/30 border-purple-500 text-purple-200":"bg-bg-card border-border text-text-muted hover:text-text-primary"}`,children:["$",D]},D))})]}),r.jsx("div",{className:"text-[10.5px] font-mono text-text-muted",children:Ce>0?r.jsxs("span",{children:["ℹ️ $",j.toFixed(2)," USD ≈ ",r.jsxs("strong",{className:"text-purple-300",children:[(j/Ce*100).toFixed(1),"%"]})," dari total equity ($",Ce.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2}),")"]}):r.jsxs("span",{children:["ℹ️ Nominal margin tetap $",j.toFixed(2)," USD"]})})]})}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex-1",children:[r.jsxs("div",{className:"flex items-center justify-between text-[10px] text-text-muted mb-1",children:[r.jsx("span",{className:"uppercase font-bold",children:"Leverage:"}),r.jsxs("span",{className:"font-mono text-purple-300 font-bold",children:[C,"x"]})]}),r.jsx("input",{type:"range",min:"1",max:"25",step:"1",value:C,onChange:D=>M(parseInt(D.target.value,10)),className:"w-full accent-purple-500 cursor-pointer"})]}),r.jsxs("div",{className:"flex items-center rounded-lg border border-border bg-bg-card p-0.5 shrink-0 self-end",children:[r.jsx("button",{type:"button",onClick:()=>f("Limit"),className:`px-2.5 py-1.5 rounded-md text-[10px] font-bold transition-all ${b==="Limit"?"bg-purple-600 text-white shadow-sm":"text-text-muted"}`,children:"Limit"}),r.jsx("button",{type:"button",onClick:()=>f("Market"),className:`px-2.5 py-1.5 rounded-md text-[10px] font-bold transition-all ${b==="Market"?"bg-purple-600 text-white shadow-sm":"text-text-muted"}`,children:"Market"})]})]})]})]}),r.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[r.jsxs("div",{className:"p-2.5 rounded-xl bg-bg-card border border-border space-y-1",children:[r.jsx("span",{className:"text-[9px] uppercase font-bold text-text-muted block",children:b==="Limit"?"ENTRY PRICE (LIMIT)":"ENTRY MARKET"}),r.jsx("input",{type:"number",step:"any",disabled:b==="Market",value:L,onChange:D=>I(parseFloat(D.target.value)||0),className:"w-full px-2 py-1 rounded bg-bg-elevated border border-border text-xs font-mono font-bold text-text-primary focus:border-purple-500 focus:outline-none disabled:opacity-50"})]}),r.jsxs("div",{className:"p-2.5 rounded-xl bg-rose-500/10 border border-rose-500/25 space-y-1",children:[r.jsxs("span",{className:"text-[9px] uppercase font-bold text-rose-300/80 flex items-center justify-between",children:[r.jsx("span",{children:"STOP LOSS (SL)"}),r.jsx(Tt,{size:11,className:"text-rose-400"})]}),r.jsx("input",{type:"number",step:"any",value:R,onChange:D=>T(parseFloat(D.target.value)||0),className:"w-full px-2 py-1 rounded bg-bg-elevated border border-rose-500/40 text-xs font-mono font-bold text-rose-400 focus:border-rose-400 focus:outline-none"})]}),r.jsxs("div",{className:"p-2.5 rounded-xl bg-emerald-500/10 border border-emerald-500/25 space-y-1",children:[r.jsxs("span",{className:"text-[9px] uppercase font-bold text-emerald-300/80 flex items-center justify-between",children:[r.jsx("span",{children:"TARGET TP1"}),r.jsx(Ye,{size:11,className:"text-emerald-400"})]}),r.jsx("input",{type:"number",step:"any",value:E,onChange:D=>F(parseFloat(D.target.value)||0),className:"w-full px-2 py-1 rounded bg-bg-elevated border border-emerald-500/40 text-xs font-mono font-bold text-emerald-400 focus:border-emerald-400 focus:outline-none"})]}),r.jsxs("div",{className:"p-2.5 rounded-xl bg-emerald-500/10 border border-emerald-500/25 space-y-1",children:[r.jsxs("span",{className:"text-[9px] uppercase font-bold text-emerald-300/80 flex items-center justify-between",children:[r.jsx("span",{children:"TARGET TP2"}),r.jsx(Ye,{size:11,className:"text-emerald-400"})]}),r.jsx("input",{type:"number",step:"any",value:B||"",onChange:D=>z(D.target.value?parseFloat(D.target.value):null),placeholder:"Opsional",className:"w-full px-2 py-1 rounded bg-bg-elevated border border-emerald-500/40 text-xs font-mono font-bold text-emerald-300 focus:border-emerald-400 focus:outline-none"})]})]}),r.jsxs("div",{className:"p-3.5 rounded-xl bg-purple-950/20 border border-purple-500/30 space-y-2.5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("span",{className:"text-[11px] font-bold uppercase tracking-wider text-purple-200 flex items-center gap-1.5",children:[r.jsx(Ae,{size:13,className:"text-purple-400"}),"Porsi Ambil Cuan TP1 (Custom Split)"]}),r.jsx("div",{className:"flex items-center gap-1",children:[25,50,75,100].map(D=>r.jsxs("button",{type:"button",onClick:()=>q(D),className:`px-2 py-0.5 rounded text-[10px] font-mono font-bold transition-all ${V===D?"bg-purple-600 text-white shadow-sm":"bg-bg-card border border-border text-text-muted hover:text-text-primary"}`,children:[D,"%"]},D))})]}),r.jsxs("div",{className:"space-y-1",children:[r.jsx("input",{type:"range",min:"10",max:"100",step:"5",value:V,onChange:D=>q(parseInt(D.target.value,10)),className:"w-full accent-purple-500 cursor-pointer"}),r.jsxs("div",{className:"flex items-center justify-between text-[10px] font-mono text-purple-300/90",children:[r.jsxs("span",{children:["TP1: ",V,"%"]}),r.jsx("span",{children:V<100?`TP2: ${100-V}%`:"TP2: Dinonaktifkan"})]})]}),r.jsx("p",{className:"text-[11px] text-purple-200/90 leading-tight",children:V>=100?r.jsxs("span",{children:["🎯 100% posisi akan ditutup penuh di ",r.jsx("strong",{children:"TP1"})," saat harga tercapai."]}):r.jsxs("span",{children:["🎯 ",r.jsxs("strong",{children:[V,"%"]})," posisi akan ditutup di ",r.jsx("strong",{children:"TP1"})," ($",E,"), dan sisa ",r.jsxs("strong",{children:[100-V,"%"]})," dibiarkan berlari ke ",r.jsx("strong",{children:"TP2"})," ($",B||"Runner",")."]})}),V<100&&!!B&&r.jsx("div",{className:"pt-2 border-t border-purple-500/20 flex items-start justify-between gap-3",children:r.jsxs("label",{className:"flex items-start gap-2 cursor-pointer select-none",children:[r.jsx("input",{type:"checkbox",checked:J,onChange:D=>oe(D.target.checked),className:"mt-0.5 accent-emerald-500 rounded cursor-pointer"}),r.jsxs("div",{className:"space-y-0.5",children:[r.jsx("span",{className:"text-[11px] font-bold text-emerald-300 block",children:"🛡️ Auto-Breakeven SL setelah TP1 (+6 bps Fee Buffer)"}),r.jsx("span",{className:"text-[10px] text-text-muted block leading-snug",children:"Saat TP1 tercapai, SL sisa runner otomatis digeser ke Harga Entry ±6 bps (aktif 12 jam di server persistent; manual di mode serverless)."})]})]})})]}),r.jsxs("div",{className:"p-3 rounded-xl bg-bg-elevated/40 border border-border flex flex-wrap items-center justify-between gap-3 text-xs",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-[10px] text-text-muted uppercase font-bold block",children:"POTENSI CUAN TOTAL"}),r.jsxs("span",{className:"text-sm font-bold font-mono text-emerald-400",children:["+$",Tr.toFixed(2)," USD"]})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-[10px] text-text-muted uppercase font-bold block",children:"MAKSIMAL RISIKO (SL)"}),r.jsxs("span",{className:"text-sm font-bold font-mono text-rose-400",children:["-$",Math.abs(bi).toFixed(2)," USD"]})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-[10px] text-text-muted uppercase font-bold block",children:"RISK / REWARD RIIL"}),r.jsxs("span",{className:"text-sm font-bold font-mono text-purple-300",children:["1 : ",So]})]})]}),r.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2 border-t border-border/50",children:[r.jsx(se,{variant:"ghost",size:"md",onClick:e,disabled:_,children:"Batal"}),r.jsx(se,{variant:"primary",size:"md",onClick:ko,loading:_,icon:r.jsx(Ae,{size:15}),className:"bg-purple-600 hover:bg-purple-500 text-white font-bold px-5 shadow-lg shadow-purple-600/30",children:"Eksekusi Order ke Bybit"})]})]})})}function Wh(s){return s?s.replace(/\*\*/g,"").replace(/^[•\s:–—-]+|[•\s:–—-]+$/g,"").trim():""}function Ne(s,e){for(const t of e){const i=s.match(t);if(i&&i[1]){const n=Wh(i[1]);if(n)return n}}return""}function Hh(s,e,t,i){if(!s||typeof s!="string")return null;const n=/Zona Entry|Entry Zone|Actionable Trade Setup|Rencana Trading|Dynamic Stop Loss/i.test(s),a=/EXECUTIVE VERDICT|Executive Summary|Ringkasan Eksekutif|Directional Bias/i.test(s);if(!n&&!a)return null;let o=Ne(s,[/(?:Directional\s+)?Bias[:\s*]+([^\n\r]+)/i,/EXECUTIVE VERDICT.*?Bias[:\s*]+([^\n\r]+)/is]);!o&&e&&(o=e);let l=Ne(s,[/Ringkasan Eksekutif(?:\s*\([^)]*\))?[:\s*]+([^\n\r]+)/i,/Executive Summary(?:\s*\([^)]*\))?[:\s*]+([^\n\r]+)/i,/Sintesis Padat[:\s*]+([^\n\r]+)/i]),c=Ne(s,[/Zona Entry(?:\s*\([^)]*\))?[:\s*]+([^\n\r]+)/i,/Entry Zone[:\s*]+([^\n\r]+)/i,/Entry Price[:\s*]+([^\n\r]+)/i]);!c&&i?.entry_zone&&(c=i.entry_zone);let d=Ne(s,[/(?:Dynamic\s+)?Stop Loss(?:\s*\(SL\))?[:\s*]+([^\n\r]+)/i,/\bSL[:\s*]+([^\n\r]+)/i]);!d&&i?.stop_loss_str&&(d=i.stop_loss_str);let h=Ne(s,[/Take Profit(?:\s*\([^)]*\))?[:\s*]+([^\n\r]+)/i,/\bTP[:\s*]+([^\n\r]+)/i]),u="",m="";if(h){const C=h.match(/TP1\s*[:\s]*(\$?[0-9,.]+)/i),M=h.match(/TP2\s*[:\s]*(\$?[0-9,.]+)/i);C&&(u=C[1]),M&&(m=M[1])}!u&&i?.take_profit_1_str&&(u=i.take_profit_1_str),!m&&i?.take_profit_2_str&&(m=i.take_profit_2_str);let x=Ne(s,[/Risk[\s/]*Reward[:\s*]+([^\n\r]+)/i,/\bRR[:\s*]+([^\n\r]+)/i]);!x&&i?.risk_reward&&(x=i.risk_reward);let b=Ne(s,[/Rekomendasi Leverage(?: & Sizing)?[:\s*]+([^\n\r]+)/i,/Leverage(?: & Sizing)?[:\s*]+([^\n\r]+)/i,/Leverage[:\s*]+([^\n\r]+)/i]),f=Ne(s,[/Kondisi Invalidasi(?: Kritis)?[:\s*]+([^\n\r]+)/i,/Invalidasi(?: Kritis)?[:\s*]+([^\n\r]+)/i]),v=Ne(s,[/Target Sapuan Likuidasi(?:\s*\([^)]*\))?[:\s*]+([^\n\r]+)/i,/Magnet Likuidasi[:\s*]+([^\n\r]+)/i,/Liquidation Magnet[:\s*]+([^\n\r]+)/i]);!v&&t?.upper_magnet&&(v=`${t.upper_magnet} / ${t.lower_magnet}`);let p=Ne(s,[/Spot CVD vs Futures CVD(?:\s*&[^\n:]*)?[:\s*]+([^\n\r]+)/i,/Status Aliran CVD[:\s*]+([^\n\r]+)/i]);!p&&t?.cvd_verdict&&(p=t.cvd_verdict);let g=Ne(s,[/Confluence Consensus[:\s*]+([^\n\r]+)/i,/Konsensus Sinyal[:\s*]+([^\n\r]+)/i]),S=Ne(s,[/Disparitas Harga & Bursa Pendorong(?:\s*\(Lead-Lag\))?[:\s*]+([^\n\r]+)/i,/Disparitas Harga[:\s*]+([^\n\r]+)/i,/Lead-Lag[:\s*]+([^\n\r]+)/i]);!S&&t?.lead_lag_spread_bps!==void 0&&(S=`${t.lead_lag_spread_bps.toFixed(1)} bps (${t.leading_exchange?.toUpperCase()||"BALANCED"})`);let j=Ne(s,[/Funding Rate,\s*(?:Countdown\s+)?Settlement(?: & Carry)?(?:\s*\(APR\))?[:\s*]+([^\n\r]+)/i,/Jadwal Settlement Terdekat[:\s*]+([^\n\r]+)/i,/Countdown Settlement[:\s*]+([^\n\r]+)/i]);!j&&t?.funding_countdown&&(j=t.funding_countdown);let k=Ne(s,[/Radar Squeeze & Breakout[:\s*]+([^\n\r]+)/i,/Energi Volatilitas & Profil 24 Jam[:\s*]+([^\n\r]+)/i,/Squeeze Radar[:\s*]+([^\n\r]+)/i]);return!k&&t?.breakout_radar?.is_breakout_primed&&(k=`${t.breakout_radar.radar_label} (${t.breakout_radar.squeeze_stage})`),o||c||d||l?{bias:o||"ANALYZED",verdictSummary:l||"Analisa kuantitatif selesai dihitung.",entryZone:c||"Sesuai level S/R terdekat",stopLoss:d||"Lihat SL di narasi analisa",takeProfit1:u,takeProfit2:m,takeProfitRaw:h||(u?`TP1: ${u} | TP2: ${m}`:"Lihat TP di analisa"),riskReward:x||"1 : 1.5+",leverage:b||"2x - 3x aman",invalidation:f||"Penutupan candle 1H berlawanan arah bias",liquidationMagnet:v,flowStatus:p,confluenceConsensus:g,leadLag:S,fundingSettlement:j,breakoutRadar:k}:null}function Vh(s){const e=(s||"").toUpperCase();return e.includes("STRONG LONG")||e.includes("STRONG BUY")?{theme:"long",badgeBg:"bg-emerald-500/20 text-emerald-300 border-emerald-500/40",borderGlow:"border-emerald-500/40 hover:border-emerald-500/60 shadow-emerald-950/30",gradientBg:"from-emerald-950/25 via-bg-elevated/40 to-bg-card",icon:Qe,accentText:"text-emerald-400",glowDot:"bg-emerald-400 shadow-emerald-400/50"}:e.includes("LONG")||e.includes("BUY")?{theme:"long",badgeBg:"bg-cyan-500/20 text-cyan-300 border-cyan-500/40",borderGlow:"border-cyan-500/40 hover:border-cyan-500/60 shadow-cyan-950/30",gradientBg:"from-cyan-950/20 via-bg-elevated/40 to-bg-card",icon:Qe,accentText:"text-cyan-400",glowDot:"bg-cyan-400 shadow-cyan-400/50"}:e.includes("STRONG SHORT")||e.includes("STRONG SELL")?{theme:"short",badgeBg:"bg-rose-500/20 text-rose-300 border-rose-500/40",borderGlow:"border-rose-500/40 hover:border-rose-500/60 shadow-rose-950/30",gradientBg:"from-rose-950/25 via-bg-elevated/40 to-bg-card",icon:Mt,accentText:"text-rose-400",glowDot:"bg-rose-400 shadow-rose-400/50"}:e.includes("SHORT")||e.includes("SELL")?{theme:"short",badgeBg:"bg-rose-500/20 text-rose-300 border-rose-500/40",borderGlow:"border-rose-500/40 hover:border-rose-500/60 shadow-rose-950/30",gradientBg:"from-rose-950/20 via-bg-elevated/40 to-bg-card",icon:Mt,accentText:"text-rose-400",glowDot:"bg-rose-400 shadow-rose-400/50"}:{theme:"neutral",badgeBg:"bg-amber-500/20 text-amber-300 border-amber-500/40",borderGlow:"border-amber-500/30 hover:border-amber-500/50 shadow-amber-950/30",gradientBg:"from-amber-950/20 via-bg-elevated/40 to-bg-card",icon:Tt,accentText:"text-amber-400",glowDot:"bg-amber-400 shadow-amber-400/50"}}function Kh({symbol:s,content:e,bias:t,dataSnapshot:i,tradeLevels:n,modelUsed:a}){const[o,l]=y.useState(!1),[c,d]=y.useState(!1),[h,u]=y.useState(!1),[m,x]=y.useState(!1),{toast:b}=ft();y.useEffect(()=>{u(!1),l(!1)},[s,e]);const f=Hh(e,t,i,n);if(!f)return null;const v=Vh(f.bias),p=v.icon,g=()=>{const j=`⚡ [${s}] DAMIAN TRADE VERDICT: ${f.bias} -📍 Entry: ${f.entryZone} -🛑 Stop Loss: ${f.stopLoss} -🎯 Target TP: ${f.takeProfit1?`TP1: ${f.takeProfit1} | TP2: ${f.takeProfit2}`:f.takeProfitRaw} -⚖️ Risk/Reward: ${f.riskReward} -⚡ Leverage: ${f.leverage} -⚠️ Invalidasi: ${f.invalidation}`;navigator.clipboard.writeText(j),l(!0),b("Setup trading disalin ke clipboard!","success"),setTimeout(()=>l(!1),2e3)},S=async()=>{if(!(c||h)){d(!0);try{const j=await Le.logTrade({symbol:s,bias:f.bias,entry_zone:f.entryZone,stop_loss:f.stopLoss,take_profit:f.takeProfit1?`TP1: ${f.takeProfit1} | TP2: ${f.takeProfit2}`:f.takeProfitRaw,risk_reward:f.riskReward,leverage:f.leverage,invalidation:f.invalidation,summary_tldr:f.verdictSummary,full_analysis:e,model_used:a,snapshot_data:i});u(!0),j?.entry&&window.dispatchEvent(new CustomEvent("journal-updated",{detail:j.entry})),b(`[${s}] Setup trading berhasil dicatat ke Jurnal!`,"success")}catch(j){b(j.message||"Gagal menyimpan ke Jurnal","error")}finally{d(!1)}}};return r.jsxs("div",{className:`rounded-2xl border bg-gradient-to-b ${v.gradientBg} ${v.borderGlow} p-4 sm:p-5 space-y-4 shadow-md transition-all animate-fade-in relative overflow-hidden`,children:[r.jsx("div",{className:"absolute top-0 left-0 right-0 h-[2px] bg-gradient-to-r from-transparent via-purple-500 to-transparent opacity-70"}),r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2.5 pb-3 border-b border-border/50",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("div",{className:"p-1.5 rounded-lg bg-purple-500/20 text-purple-300 flex items-center justify-center",children:r.jsx(Fo,{size:15})}),r.jsxs("div",{children:[r.jsx("span",{className:"text-[10px] uppercase font-bold tracking-wider text-purple-300 block",children:"Kesimpulan Eksekutif Damian"}),r.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[r.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-mono font-bold border ${v.badgeBg}`,children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full shadow-sm animate-pulse ${v.glowDot}`}),r.jsx(p,{size:12}),r.jsx("span",{children:f.bias})]}),r.jsx("span",{className:"text-[11px] font-mono text-text-muted font-bold",children:s})]})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[r.jsxs("button",{type:"button",onClick:()=>x(!0),className:"px-3 py-1.5 rounded-lg border border-purple-500/50 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white text-[11px] font-bold flex items-center gap-1.5 transition-all shadow-md shadow-purple-600/25 active:scale-95 group",title:"Eksekusi setup ini secara presisi ke bursa",children:[r.jsx(Ae,{size:12,className:"text-yellow-300 fill-yellow-300 group-hover:scale-110 transition-transform"}),r.jsx("span",{children:"Eksekusi Order"})]}),r.jsx("button",{type:"button",onClick:S,disabled:c||h,className:`px-2.5 py-1.5 rounded-lg border text-[11px] font-medium flex items-center gap-1.5 transition-all shadow-sm ${h?"bg-emerald-500/15 border-emerald-500/40 text-emerald-300 cursor-default":"border-purple-500/40 bg-purple-600/20 hover:bg-purple-600/30 text-purple-200"}`,title:"Catat trade ini ke Jurnal untuk ditrack hasilnya",children:h?r.jsxs(r.Fragment,{children:[r.jsx(rt,{size:12,className:"text-emerald-400"}),r.jsx("span",{className:"font-semibold text-emerald-300",children:"Tercatat di Jurnal"})]}):r.jsxs(r.Fragment,{children:[r.jsx(Uo,{size:12,className:"text-purple-300"}),r.jsx("span",{children:"📌 Catat ke Jurnal"})]})}),r.jsx("button",{type:"button",onClick:g,className:"px-2.5 py-1.5 rounded-lg border border-border/80 bg-bg-card hover:bg-bg-elevated text-[11px] font-medium text-text-secondary hover:text-purple-300 flex items-center gap-1.5 transition-all shadow-sm group",title:"Salin setup order trading ke clipboard",children:o?r.jsxs(r.Fragment,{children:[r.jsx(rt,{size:12,className:"text-emerald-400"}),r.jsx("span",{className:"text-emerald-400 font-semibold",children:"Tersalin!"})]}):r.jsxs(r.Fragment,{children:[r.jsx(es,{size:12,className:"text-text-muted group-hover:text-purple-400 transition-colors"}),r.jsx("span",{children:"Salin Order"})]})})]})]}),f.verdictSummary&&r.jsxs("div",{className:"p-3 rounded-xl bg-purple-500/10 border border-purple-500/20 text-xs text-text-primary leading-relaxed flex items-start gap-2.5",children:[r.jsx(Fe,{size:15,className:"text-purple-400 shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("span",{className:"font-semibold text-purple-200 block text-[11px] mb-0.5",children:"💡 Intisari Pasar (TL;DR):"}),r.jsx("span",{className:"text-text-primary",children:f.verdictSummary})]})]}),r.jsxs("div",{className:"grid grid-cols-1 xs:grid-cols-2 lg:grid-cols-4 gap-2.5",children:[r.jsxs("div",{className:"p-3 rounded-xl bg-bg-elevated/70 border border-border/80 flex flex-col justify-between space-y-1",children:[r.jsxs("div",{className:"flex items-center justify-between text-text-muted",children:[r.jsx("span",{className:"text-[9px] uppercase font-bold tracking-wider",children:"ZONA ENTRY"}),r.jsx(lr,{size:12,className:"text-purple-400"})]}),r.jsx("div",{className:"text-xs sm:text-sm font-bold font-mono text-text-primary break-words",children:f.entryZone}),r.jsx("span",{className:"text-[9px] text-text-muted",children:"Area konfirmasi pullback S/R"})]}),r.jsxs("div",{className:"p-3 rounded-xl bg-rose-500/10 border border-rose-500/25 flex flex-col justify-between space-y-1",children:[r.jsxs("div",{className:"flex items-center justify-between text-rose-300/80",children:[r.jsx("span",{className:"text-[9px] uppercase font-bold tracking-wider",children:"STOP LOSS (SL)"}),r.jsx(Tt,{size:12,className:"text-rose-400"})]}),r.jsx("div",{className:"text-xs sm:text-sm font-bold font-mono text-rose-400 break-words",children:f.stopLoss}),r.jsx("span",{className:"text-[9px] text-rose-300/70",children:"Di luar zona wick hunt"})]}),r.jsxs("div",{className:"p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/25 flex flex-col justify-between space-y-1",children:[r.jsxs("div",{className:"flex items-center justify-between text-emerald-300/80",children:[r.jsx("span",{className:"text-[9px] uppercase font-bold tracking-wider",children:"TARGET CUAN (TP)"}),r.jsx(Ye,{size:12,className:"text-emerald-400"})]}),r.jsx("div",{className:"text-xs sm:text-sm font-bold font-mono text-emerald-400 break-words",children:f.takeProfit1?r.jsxs("div",{className:"space-y-0.5",children:[r.jsxs("span",{className:"block",children:["TP1: ",f.takeProfit1]}),f.takeProfit2&&r.jsxs("span",{className:"block text-[11px] text-emerald-300/90 font-medium",children:["TP2: ",f.takeProfit2]})]}):f.takeProfitRaw}),r.jsx("span",{className:"text-[9px] text-emerald-300/70",children:"Target magnet likuidasi"})]}),r.jsxs("div",{className:"p-3 rounded-xl bg-purple-500/10 border border-purple-500/25 flex flex-col justify-between space-y-1",children:[r.jsxs("div",{className:"flex items-center justify-between text-purple-300/80",children:[r.jsx("span",{className:"text-[9px] uppercase font-bold tracking-wider",children:"RISK / REWARD & LEV"}),r.jsx(qo,{size:12,className:"text-purple-400"})]}),r.jsxs("div",{className:"text-xs sm:text-sm font-bold font-mono text-purple-300 break-words",children:["R:R ",f.riskReward]}),r.jsxs("div",{className:"flex items-start gap-1 text-[10px] text-purple-200/80 font-mono",children:[r.jsx(Ae,{size:10,className:"text-purple-400 shrink-0 mt-0.5"}),r.jsx("span",{className:"break-words leading-tight",children:f.leverage})]})]})]}),f.invalidation&&r.jsxs("div",{className:"px-3 py-2 rounded-xl bg-amber-500/10 border border-amber-500/25 text-[11px] text-amber-200 flex items-start gap-2",children:[r.jsx(ve,{size:13,className:"text-amber-400 shrink-0 mt-0.5"}),r.jsxs("div",{className:"leading-tight",children:[r.jsx("span",{className:"font-semibold text-amber-300 mr-1.5",children:"Syarat Batal (Invalidasi):"}),r.jsx("span",{className:"text-amber-100/90",children:f.invalidation})]})]}),(f.liquidationMagnet||f.flowStatus||f.confluenceConsensus||f.leadLag||f.fundingSettlement||f.breakoutRadar)&&r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1 text-[10px] font-mono text-text-muted",children:[f.breakoutRadar&&r.jsxs("div",{className:"px-2 py-0.5 rounded-md bg-purple-500/20 border border-purple-500/40 text-purple-300 flex items-center gap-1 animate-pulse",children:[r.jsx("span",{className:"text-yellow-400",children:"🚨 Squeeze:"}),r.jsx("span",{className:"font-semibold text-purple-200",children:f.breakoutRadar})]}),f.liquidationMagnet&&r.jsxs("div",{className:"px-2 py-0.5 rounded-md bg-bg-card border border-border flex items-center gap-1",children:[r.jsx("span",{className:"text-purple-400",children:"🧲 Magnet:"}),r.jsx("span",{className:"text-text-primary font-medium",children:f.liquidationMagnet})]}),f.flowStatus&&r.jsxs("div",{className:"px-2 py-0.5 rounded-md bg-bg-card border border-border flex items-center gap-1",children:[r.jsx("span",{className:"text-cyan-400",children:"🌊 Flow:"}),r.jsx("span",{className:"text-text-primary font-medium",children:f.flowStatus})]}),f.confluenceConsensus&&r.jsxs("div",{className:"px-2 py-0.5 rounded-md bg-bg-card border border-border flex items-center gap-1",children:[r.jsx("span",{className:"text-emerald-400",children:"🎯 Konsensus:"}),r.jsx("span",{className:"text-text-primary font-medium",children:f.confluenceConsensus})]}),f.leadLag&&r.jsxs("div",{className:"px-2 py-0.5 rounded-md bg-bg-card border border-border flex items-center gap-1",children:[r.jsx("span",{className:"text-cyan-400",children:"⚡ Lead-Lag:"}),r.jsx("span",{className:"text-text-primary font-medium",children:f.leadLag})]}),f.fundingSettlement&&r.jsxs("div",{className:"px-2 py-0.5 rounded-md bg-bg-card border border-border flex items-center gap-1",children:[r.jsx("span",{className:"text-amber-400",children:"⏱️ Settle:"}),r.jsx("span",{className:"text-text-primary font-medium",children:f.fundingSettlement})]})]}),r.jsx(Ka,{isOpen:m,onClose:()=>x(!1),symbol:s,summary:f,markPrice:i?.mark_price,onExecutionSuccess:()=>{u(!0)}})]})}function Ve(s){if(!s)return null;const e=s.trim(),t=/(\*\*[^*]+?\*\*|`[^`]+`|\*[^*]+?\*|_[^_]+?_)/g;return e.split(t).map((n,a)=>{if(!n)return null;if(n.startsWith("**")&&n.endsWith("**")&&n.length>=4){const l=n.slice(2,-2).trim(),c=l.toUpperCase();return c.includes("BUY ON PULLBACK")||c.includes("STRONG LONG")||c.includes("STRONG BUY")||c==="LONG"||c==="BUY"?r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[11px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 shadow-sm align-middle mx-0.5",children:[r.jsx(Qe,{size:11,className:"text-emerald-400"}),r.jsx("span",{children:l})]},a):c.includes("SELL ON RALLY")||c.includes("STRONG SHORT")||c.includes("STRONG SELL")||c==="SHORT"||c==="SELL"?r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[11px] font-mono font-bold bg-rose-500/20 text-rose-300 border border-rose-500/40 shadow-sm align-middle mx-0.5",children:[r.jsx(Mt,{size:11,className:"text-rose-400"}),r.jsx("span",{children:l})]},a):c.includes("WAIT-AND-SEE")||c.includes("WAIT AND SEE")||c.includes("WAIT & SEE")||c==="NEUTRAL"?r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[11px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/40 shadow-sm align-middle mx-0.5",children:[r.jsx(Tt,{size:11,className:"text-amber-400"}),r.jsx("span",{children:l})]},a):r.jsx("strong",{className:"font-bold text-text-primary",children:l},a)}if(n.startsWith("`")&&n.endsWith("`")&&n.length>=2)return r.jsx("code",{className:"font-mono text-[11px] bg-bg-elevated px-1.5 py-0.5 rounded text-amber-300 border border-border/60 mx-0.5 font-semibold",children:n.slice(1,-1)},a);if(n.startsWith("*")&&n.endsWith("*")&&n.length>=2||n.startsWith("_")&&n.endsWith("_")&&n.length>=2)return r.jsx("em",{className:"italic text-text-secondary",children:n.slice(1,-1)},a);const o=n.replace(/\*\*/g,"");return r.jsx("span",{children:o},a)})}function Gh(s){const e=s.toUpperCase();return e.includes("EXECUTIVE")||e.includes("VERDICT")||e.includes("🏛️")?{border:"border-purple-500/30",bg:"bg-purple-950/15",badgeBg:"bg-purple-500/20 text-purple-300 border-purple-500/30",icon:r.jsx(Fe,{size:14,className:"text-purple-400"}),dot:"bg-purple-400"}:e.includes("ANATOMI")||e.includes("MODAL")||e.includes("CVD")||e.includes("🌊")?{border:"border-cyan-500/30",bg:"bg-cyan-950/15",badgeBg:"bg-cyan-500/20 text-cyan-300 border-cyan-500/30",icon:r.jsx(Wo,{size:14,className:"text-cyan-400"}),dot:"bg-cyan-400"}:e.includes("MIKROSTRUKTUR")||e.includes("VOLATILITAS")||e.includes("MAGNET")||e.includes("🧲")?{border:"border-amber-500/30",bg:"bg-amber-950/15",badgeBg:"bg-amber-500/20 text-amber-300 border-amber-500/30",icon:r.jsx(Ho,{size:14,className:"text-amber-400"}),dot:"bg-amber-400"}:e.includes("SETUP")||e.includes("ACTIONABLE")||e.includes("TRADE")||e.includes("🎯")?{border:"border-emerald-500/30",bg:"bg-emerald-950/15",badgeBg:"bg-emerald-500/20 text-emerald-300 border-emerald-500/30",icon:r.jsx(lr,{size:14,className:"text-emerald-400"}),dot:"bg-emerald-400"}:e.includes("PENGAMAN")||e.includes("MEMORI")||e.includes("EVALUASI")||e.includes("🛡️")?{border:"border-rose-500/30",bg:"bg-rose-950/15",badgeBg:"bg-rose-500/20 text-rose-300 border-rose-500/30",icon:r.jsx(yt,{size:14,className:"text-rose-400"}),dot:"bg-rose-400"}:{border:"border-border/80",bg:"bg-bg-elevated/40",badgeBg:"bg-bg-elevated text-text-primary border-border",icon:r.jsx(Fe,{size:14,className:"text-purple-400"}),dot:"bg-purple-400"}}function Qh(s){const e=s.trim();return e?!!(e.startsWith("#")||e.startsWith("===")&&e.endsWith("===")||/^(?:[^\w\s]+\s*)?\d+\.\s+[A-Z\s/()&,.-]{4,}/u.test(e)||/^[^\w\s]+\s+[A-Z\s/()&,.-]{5,}/u.test(e)):!1}function Ga({content:s,className:e=""}){if(!s)return null;const t=s.split(/\r?\n/),i=[];let n={id:"intro",title:"",rawHeader:"",items:[]};for(const a of t){const o=a.trim();o&&(Qh(o)?((n.title||n.items.length>0)&&i.push(n),n={id:`sec-${i.length}`,title:o.replace(/^#+\s*/,"").replace(/^===\s*/,"").replace(/\s*===$/,""),rawHeader:o,items:[]}):n.items.push(o))}return(n.title||n.items.length>0)&&i.push(n),i.length===1&&!i[0].title?r.jsx("div",{className:`space-y-2 text-xs sm:text-[13px] text-text-primary leading-relaxed ${e}`,children:i[0].items.map((a,o)=>r.jsx("p",{children:Ve(a)},o))}):r.jsx("div",{className:`space-y-3 font-sans text-xs sm:text-[13px] ${e}`,children:i.map((a,o)=>{const l=Gh(a.title);return r.jsxs("div",{className:`rounded-xl border p-3.5 space-y-2.5 transition-all shadow-sm ${l.border} ${l.bg}`,children:[a.title&&r.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b border-border/40",children:[r.jsx("span",{className:"p-1 rounded-md bg-bg-card/80 border border-border/50 shrink-0",children:l.icon}),r.jsx("h4",{className:"font-bold text-xs sm:text-sm font-mono text-text-primary tracking-tight",children:Ve(a.title)})]}),r.jsx("div",{className:"space-y-2",children:a.items.map((c,d)=>{const h=c.match(/^[-*•]\s*\*\*([^*]+?)\*\*[:\s]+(.*)$/);if(h){const m=h[1].trim(),x=h[2].trim();return r.jsxs("div",{className:"flex items-start gap-2 text-xs sm:text-[13px] leading-relaxed group",children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full mt-2 shrink-0 ${l.dot}`}),r.jsxs("div",{className:"flex-1",children:[r.jsxs("span",{className:"font-semibold text-purple-200 mr-1.5",children:[m,":"]}),r.jsx("span",{className:"text-text-primary/95",children:Ve(x)})]})]},d)}if(c.startsWith("- ")||c.startsWith("* ")||c.startsWith("• ")){const m=c.replace(/^[-*•]\s+/,"").trim();return r.jsxs("div",{className:"flex items-start gap-2 text-xs sm:text-[13px] leading-relaxed",children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full mt-2 shrink-0 ${l.dot}`}),r.jsx("div",{className:"flex-1 text-text-primary/95",children:Ve(m)})]},d)}const u=c.match(/^(\d+)\.\s+(.*)$/);if(u){const m=u[1],x=u[2].trim(),b=x.match(/^\*\*([^*]+?)\*\*[:\s]+(.*)$/);if(b){const f=b[1].trim(),v=b[2].trim();return r.jsxs("div",{className:"flex items-start gap-2.5 text-xs sm:text-[13px] leading-relaxed p-2 rounded-lg bg-bg-card/50 border border-border/50",children:[r.jsx("span",{className:"px-1.5 py-0.2 rounded text-[10px] font-mono font-bold bg-bg-elevated text-purple-300 border border-border/60 shrink-0 mt-0.5",children:m}),r.jsxs("div",{className:"flex-1",children:[r.jsxs("span",{className:"font-bold text-purple-200 mr-1.5",children:[f,":"]}),r.jsx("span",{className:"text-text-primary/95",children:Ve(v)})]})]},d)}return r.jsxs("div",{className:"flex items-start gap-2.5 text-xs sm:text-[13px] leading-relaxed p-2 rounded-lg bg-bg-card/50 border border-border/50",children:[r.jsx("span",{className:"px-1.5 py-0.2 rounded text-[10px] font-mono font-bold bg-bg-elevated text-purple-300 border border-border/60 shrink-0 mt-0.5",children:m}),r.jsx("div",{className:"flex-1 text-text-primary/95",children:Ve(x)})]},d)}return c.startsWith("⚠️")||c.startsWith("🚨")||c.toUpperCase().startsWith("WARNING:")?r.jsxs("div",{className:"p-2.5 rounded-lg bg-amber-500/10 border border-amber-500/30 text-amber-200 text-xs sm:text-[12px] flex items-start gap-2",children:[r.jsx(ve,{size:14,className:"text-amber-400 shrink-0 mt-0.5"}),r.jsx("div",{className:"leading-snug",children:Ve(c)})]},d):r.jsx("p",{className:"text-text-primary/95 leading-relaxed",children:Ve(c)},d)})})]},a.id||o)})})}const Yh=y.lazy(()=>pt(()=>import("./GlobalAISettingsModal-y_W5Q-P7.js"),__vite__mapDeps([5,1,2,3])).then(s=>({default:s.GlobalAISettingsModal}))),an=[{label:"⚡ Setup Scalp 15m",prompt:"Berikan analisa scalping timeframe 15m, apakah ada momentum masuk saat ini dan di level berapa entry amannya?"},{label:"🧲 Cek Likuidasi & Trap",prompt:"Analisa kolam likuidasi (magnet harga) dan apakah ada jebakan leverage trap antara Spot vs Futures CVD?"},{label:"🛡️ Validasi Fake Breakout",prompt:"Periksa apakah ada tanda-tanda manipulasi harga, fake pump/dump, atau wick sweep pada pair ini?"},{label:"📋 Rencana Trading Lengkap",prompt:"Buatkan rencana trading institusional: Entry Zone terkonfirmasi, Stop Loss ketat, Take Profit 1 & 2, serta kondisi pembatalan setup."}];function Jh(s){if(!s)return"bg-gray-500/20 text-gray-300 border-gray-500/30";const e=s.toUpperCase();return e.includes("STRONG LONG")||e.includes("STRONG BUY")?"bg-emerald-500/20 text-emerald-300 border-emerald-500/40":e.includes("LONG")?"bg-signal-long/20 text-signal-long border-signal-long/30":e.includes("STRONG SHORT")||e.includes("STRONG SELL")?"bg-rose-500/20 text-rose-300 border-rose-500/40":e.includes("SHORT")?"bg-signal-short/20 text-signal-short border-signal-short/30":"bg-amber-500/20 text-amber-300 border-amber-500/30"}function Xh({initialSymbol:s="BTCUSDT",onSelectSymbol:e}){const{data:t=[],isLoading:i}=us(),{data:n=[]}=li(),{settings:a,isConfigured:o}=ci(),{toast:l}=ft(),c=y.useMemo(()=>t.filter(N=>N.is_active),[t]),[d,h]=y.useState(()=>s&&t.some(N=>N.symbol===s)?s:c[0]?.symbol||"BTCUSDT"),u=N=>{h(N),e&&e(N)};y.useEffect(()=>{s&&s!==d&&h(s)},[s]);const[m,x]=y.useState(""),[b,f]=y.useState("ALL"),[v,p]=y.useState({}),[g,S]=y.useState(""),[j,k]=y.useState(!1),[C,M]=y.useState(null),[L,I]=y.useState({}),[R,T]=y.useState({}),E=N=>{T(U=>({...U,[N]:!U[N]}))},F=y.useRef(null),B=y.useMemo(()=>n.find(N=>N.symbol===d),[n,d]),z=y.useMemo(()=>new Map(n.map(N=>[N.symbol,N])),[n]),V=y.useMemo(()=>c.filter(N=>{if(!(N.symbol.toLowerCase().includes(m.toLowerCase().trim())||N.display_name.toLowerCase().includes(m.toLowerCase().trim())))return!1;const A=z.get(N.symbol);return b==="SPOT_ONLY"?A?.has_spot===!0:b==="PERP_ONLY"?A?.has_spot===!1:b==="HOT"?(A?.conviction??0)>=4:b==="LONG"?A?.direction==="LONG":b==="SHORT"?A?.direction==="SHORT":!0}),[c,m,b,z]),q=v[d]||{messages:[],isLoading:!1,error:null};y.useEffect(()=>{F.current?.scrollIntoView({behavior:"smooth"})},[q.messages.length,q.isLoading]);const J=async(N,U=!1)=>{const A=(N!==void 0?N:g).trim();if(!A&&q.messages.length>0&&!U)return;if(!o){k(!0),l("Silakan masukkan API Key AI Anda terlebih dahulu","error");return}const ee=`user-${Date.now()}`,xe=A?{id:ee,role:"user",content:A,timestamp:new Date().toLocaleTimeString("id-ID",{hour:"2-digit",minute:"2-digit"})}:null;p(K=>{const te=K[d]||{messages:[],isLoading:!1,error:null};return{...K,[d]:{...te,messages:xe?[...te.messages,xe]:te.messages,isLoading:!0,error:null}}}),N||S("");try{const K=await Dh.analyze({symbol:d,provider:a.provider,model:a.model,api_key:a.api_key,base_url:a.base_url,question:A||void 0,force_refresh:U,max_tokens:a.max_tokens}),te={id:`ai-${Date.now()}`,role:"assistant",content:K.analysis,timestamp:new Date().toLocaleTimeString("id-ID",{hour:"2-digit",minute:"2-digit"}),bias:K.bias,model:K.model,isCached:K.is_cached,cacheAgeSeconds:K.cache_age_seconds,dataSnapshot:K.data_snapshot};p(be=>{const Se=be[d]||{messages:[],isLoading:!1,error:null};return{...be,[d]:{...Se,messages:[...Se.messages,te],isLoading:!1,error:null}}})}catch(K){const te=K?.response?.data?.detail||K?.message||"Gagal menghubungi server AI";p(be=>{const Se=be[d]||{messages:[],isLoading:!1,error:null};return{...be,[d]:{...Se,isLoading:!1,error:te}}}),l(te,"error")}},oe=()=>{p(N=>({...N,[d]:{messages:[],isLoading:!1,error:null}})),l(`Riwayat tanya jawab untuk ${d} dibersihkan`,"success")},$=(N,U)=>{navigator.clipboard.writeText(N),M(U),l("Teks analisa berhasil disalin ke clipboard","success"),setTimeout(()=>M(null),2e3)},W=N=>{I(U=>({...U,[N]:!U[N]}))};return r.jsxs("div",{className:"flex flex-1 h-[calc(100vh-3.5rem)] overflow-hidden bg-bg-primary",children:[r.jsxs("aside",{className:"hidden md:flex w-64 lg:w-72 flex-col border-r border-border bg-bg-card shrink-0 select-none",children:[r.jsxs("div",{className:"p-3 border-b border-border space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("span",{className:"text-xs font-bold text-text-secondary uppercase tracking-wider flex items-center gap-1.5",children:[r.jsx(Be,{size:14,className:"text-purple-400"}),"Pilih Pair Analisa"]}),r.jsxs("span",{className:"text-[10px] font-mono text-purple-400 bg-purple-500/10 px-1.5 py-0.5 rounded border border-purple-500/20",children:[c.length," Pair"]})]}),r.jsxs("div",{className:"relative",children:[r.jsx(Zs,{size:13,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-text-muted"}),r.jsx("input",{type:"text",value:m,onChange:N=>x(N.target.value),placeholder:"Cari pair (e.g. BTC, SOL)...",className:"w-full bg-bg-elevated border border-border rounded-lg pl-8 pr-2.5 py-1.5 text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500/50"})]}),r.jsxs("div",{className:"flex items-center gap-1 overflow-x-auto no-scrollbar pt-0.5",children:[r.jsx("button",{onClick:()=>f("ALL"),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 ${b==="ALL"?"bg-purple-600 text-white":"bg-bg-elevated text-text-secondary hover:text-text-primary"}`,children:"Semua"}),r.jsxs("button",{onClick:()=>f("SPOT_ONLY"),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 flex items-center gap-1 ${b==="SPOT_ONLY"?"bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-semibold":"bg-bg-elevated text-text-secondary hover:text-emerald-300"}`,title:"Hanya tampilkan pair yang memiliki pasar Spot riil",children:[r.jsx(Et,{size:10,className:"text-emerald-400"}),"Aman"]}),r.jsxs("button",{onClick:()=>f("PERP_ONLY"),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 flex items-center gap-1 ${b==="PERP_ONLY"?"bg-amber-500/20 text-amber-300 border border-amber-500/40 font-semibold":"bg-bg-elevated text-text-secondary hover:text-amber-300"}`,title:"Hanya tampilkan pair PERP-ONLY tanpa Spot (Rawan manipulasi bandar)",children:[r.jsx(ve,{size:10,className:"text-amber-400"}),"Rawan"]}),r.jsxs("button",{onClick:()=>f("HOT"),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 flex items-center gap-1 ${b==="HOT"?"bg-amber-500/20 text-amber-300 border border-amber-500/40":"bg-bg-elevated text-text-secondary hover:text-amber-300"}`,children:[r.jsx(ts,{size:10}),"Hot ≥4"]}),r.jsxs("button",{onClick:()=>f("LONG"),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 flex items-center gap-1 ${b==="LONG"?"bg-signal-long/20 text-signal-long border border-signal-long/40":"bg-bg-elevated text-text-secondary hover:text-signal-long"}`,children:[r.jsx(ra,{size:10}),"Long"]}),r.jsxs("button",{onClick:()=>f("SHORT"),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 flex items-center gap-1 ${b==="SHORT"?"bg-signal-short/20 text-signal-short border border-signal-short/40":"bg-bg-elevated text-text-secondary hover:text-signal-short"}`,children:[r.jsx(na,{size:10}),"Short"]})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto custom-scrollbar p-2 space-y-1",children:[i&&r.jsx("div",{className:"p-4 text-center text-xs text-text-muted",children:"Memuat daftar pair..."}),!i&&V.length===0&&r.jsx("div",{className:"p-4 text-center text-xs text-text-muted",children:"Tidak ada pair yang cocok"}),V.map(N=>{const U=z.get(N.symbol),A=N.symbol===d,ee=v[N.symbol]?.messages?.length||0,xe=U?.direction==="LONG"?"text-signal-long bg-signal-long/10 border-signal-long/30":U?.direction==="SHORT"?"text-signal-short bg-signal-short/10 border-signal-short/30":"text-text-muted bg-bg-elevated border-border";return r.jsxs("button",{type:"button",onClick:()=>u(N.symbol),className:`w-full flex items-center justify-between p-2 rounded-xl text-xs transition-all text-left ${A?"bg-purple-600/15 border border-purple-500/50 shadow-sm text-text-primary":"hover:bg-bg-elevated/70 border border-transparent text-text-secondary hover:text-text-primary"}`,children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${U?.direction==="LONG"?"bg-signal-long shadow-sm shadow-signal-long/50":U?.direction==="SHORT"?"bg-signal-short shadow-sm shadow-signal-short/50":"bg-gray-500"}`}),r.jsxs("div",{className:"truncate",children:[r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("p",{className:`font-mono font-bold truncate ${A?"text-purple-300":"text-text-primary"}`,children:N.display_name}),U?.has_spot===!1&&r.jsx("span",{className:"text-[8px] px-1 py-0.5 rounded bg-amber-500/20 text-amber-300 font-mono font-bold shrink-0",title:"Rawan Bandar (Perp Only)",children:"⚠️ RAWAN"}),U?.has_spot===!0&&r.jsx("span",{className:"text-[8px] px-1 py-0.5 rounded bg-emerald-500/15 text-emerald-300 font-mono font-semibold shrink-0",title:"Aman (Spot Backed)",children:"🛡️ AMAN"})]}),r.jsx("p",{className:"text-[10px] text-text-muted",children:U?.trade_levels?.entry_price?`$${U.trade_levels.entry_price}`:U?.active_timeframe||"Perps"})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[ee>0&&r.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 font-mono",children:ee}),U&&r.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono font-bold border ${xe}`,children:[U.conviction,"/10"]})]})]},N.symbol)})]})]}),r.jsxs("section",{className:"flex-1 flex flex-col h-full overflow-hidden bg-bg-primary",children:[r.jsxs("div",{className:"px-3 sm:px-5 py-2.5 border-b border-border bg-bg-card flex flex-col sm:flex-row sm:items-center justify-between gap-2 shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("div",{className:"p-2 rounded-xl bg-purple-500/15 border border-purple-500/30 text-purple-400 shrink-0",children:r.jsx(Be,{size:18})}),r.jsxs("div",{className:"min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("h2",{className:"font-mono font-bold text-sm sm:text-base text-text-primary truncate hidden md:inline",children:d}),r.jsxs("div",{className:"relative md:hidden inline-flex items-center",children:[r.jsx("select",{value:d,onChange:N=>u(N.target.value),className:"opacity-0 absolute inset-0 w-full h-full cursor-pointer z-10","aria-label":"Pilih Trading Pair",children:c.map(N=>{const U=z.get(N.symbol),A=U?.direction==="LONG"?"🟢":U?.direction==="SHORT"?"🔴":"⚪";return r.jsxs("option",{value:N.symbol,children:[A," ",N.display_name," — ",U?.direction||"WAIT"," (",U?.conviction||0,"/10)"]},N.symbol)})}),r.jsxs("button",{type:"button",className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-bg-elevated border border-purple-500/40 text-xs font-mono font-bold text-purple-300 shadow-sm active:scale-95",title:"Ketuk untuk ganti pair",children:[r.jsx("span",{children:d}),r.jsx(jt,{size:12,className:"text-purple-400"})]})]}),B?.has_spot===!1&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/40 flex items-center gap-1 shrink-0",title:"Aset RAWAN BANDAR: Kontrak Perp-Only tanpa pasar Spot riil.",children:[r.jsx(ve,{size:10,className:"text-amber-400"}),"⚠️ Perp Only"]}),B?.has_spot===!0&&r.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-mono font-medium bg-emerald-500/15 text-emerald-400 border border-emerald-500/30 flex items-center gap-1 shrink-0",title:"Aset AMAN: Memiliki pasar Spot riil di bursa.",children:[r.jsx(Et,{size:10,className:"text-emerald-400"}),"🛡️ Spot"]}),B&&r.jsxs("span",{className:`px-2 py-0.5 rounded-full text-[10px] font-mono font-bold border ${B.direction==="LONG"?"bg-signal-long/15 text-signal-long border-signal-long/30":B.direction==="SHORT"?"bg-signal-short/15 text-signal-short border-signal-short/30":"bg-gray-500/15 text-text-muted border-border"}`,children:[B.direction," • ",B.conviction,"/10"]}),B?.active_timeframe&&r.jsxs("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-bg-elevated border border-border text-text-muted",children:["TF: ",B.active_timeframe.toUpperCase()]})]}),r.jsx("p",{className:"text-[10px] text-text-muted truncate",children:B?.quick_verdict||"Data live bursa tersambung & siap dianalisa AI"})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 self-end sm:self-auto shrink-0",children:[r.jsxs("button",{type:"button",onClick:()=>J(void 0,!0),disabled:q.isLoading,className:"flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-medium border border-border bg-bg-elevated hover:bg-bg-card text-text-secondary hover:text-text-primary transition-colors disabled:opacity-50",title:"Paksa hitung ulang analisa dengan token baru",children:[r.jsx(Re,{size:11,className:q.isLoading?"animate-spin":""}),r.jsx("span",{className:"hidden xs:inline",children:"Analisa Ulang"})]}),q.messages.length>0&&r.jsx("button",{type:"button",onClick:oe,className:"p-1.5 rounded-lg border border-border bg-bg-elevated hover:bg-red-500/20 hover:text-red-300 text-text-muted transition-colors",title:"Bersihkan riwayat percakapan pair ini",children:r.jsx(Qt,{size:13})}),r.jsxs("button",{type:"button",onClick:()=>k(!0),className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs border border-purple-500/30 bg-purple-500/10 hover:bg-purple-500/20 text-purple-200 transition-colors",title:"Atur Model AI & API Key",children:[r.jsx(cr,{size:12,className:"text-purple-400"}),r.jsx("span",{className:"font-mono text-[11px] truncate max-w-[100px]",children:a.model.split("/")[1]||a.model})]})]})]}),r.jsxs("div",{className:"md:hidden flex items-center gap-1.5 px-3 py-2 bg-bg-elevated/80 border-b border-border overflow-x-auto no-scrollbar shrink-0",children:[r.jsx("span",{className:"text-[10px] text-text-muted uppercase font-semibold shrink-0",children:"Pair:"}),c.map(N=>{const U=N.symbol===d,A=z.get(N.symbol);return r.jsxs("button",{onClick:()=>h(N.symbol),className:`px-2.5 py-1 rounded-lg text-xs font-mono shrink-0 transition-all ${U?"bg-purple-600 text-white font-bold shadow-sm":"bg-bg-card border border-border text-text-secondary hover:text-text-primary"}`,children:[N.symbol.replace("USDT",""),A&&r.jsx("span",{className:`ml-1 text-[10px] ${A.direction==="LONG"?"text-signal-long":A.direction==="SHORT"?"text-signal-short":"text-gray-400"}`,children:A.conviction})]},N.symbol)})]}),B?.has_spot===!1&&r.jsxs("div",{className:"mx-3 sm:mx-5 mt-3 p-2.5 rounded-xl bg-amber-500/15 border border-amber-500/30 text-xs text-amber-200 flex items-start gap-2.5 shrink-0 shadow-sm animate-fade-in",children:[r.jsx(ve,{size:15,className:"text-amber-400 shrink-0 mt-0.5"}),r.jsxs("div",{className:"leading-snug",children:[r.jsxs("span",{className:"font-bold text-amber-200",children:["⚠️ PERINGATAN RISIKO BANDAR (",d," adalah PERP-ONLY):"]}),r.jsx("p",{className:"text-[11px] text-amber-300/90 mt-0.5 leading-relaxed",children:"Koin ini tidak memiliki pasar Spot di bursa. Analisa tetap lengkap, namun harga rawan dimanipulasi wick sweep. Wajib pasang Stop Loss ketat!"})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-3 sm:p-5 space-y-4 custom-scrollbar",children:[q.messages.length===0&&!q.isLoading&&r.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[50vh] text-center max-w-xl mx-auto space-y-4 p-4 animate-fade-in",children:[r.jsx("div",{className:"w-14 h-14 rounded-2xl bg-purple-500/10 border border-purple-500/20 flex items-center justify-center text-purple-400 shadow-lg shadow-purple-500/10",children:r.jsx(Fe,{size:28})}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("h3",{className:"text-base sm:text-lg font-bold text-text-primary",children:["Damian — AI Quant Partner untuk ",d]}),r.jsx("p",{className:"text-xs text-text-secondary max-w-md mx-auto leading-relaxed",children:"Tanyakan setup trading, validasi likuidasi, atau jalankan analisa menyeluruh. Data multi-exchange (Binance, Bybit, OKX, Hyperliquid, Spot vs Fut CVD) akan disintesis otomatis secara objektif dan anti-halusinasi."})]}),r.jsx("div",{className:"pt-2",children:r.jsxs(se,{variant:"primary",size:"md",onClick:()=>J(),icon:r.jsx(Ae,{size:14}),className:"bg-purple-600 hover:bg-purple-500 text-white shadow-lg shadow-purple-500/25 px-5 py-2.5 rounded-xl font-semibold text-xs sm:text-sm",children:["Mulai Analisa Lengkap ",d]})}),r.jsxs("div",{className:"pt-4 w-full",children:[r.jsx("p",{className:"text-[11px] font-semibold text-text-muted uppercase tracking-wider mb-2",children:"Atau Pilih Topik Cepat:"}),r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-left",children:an.map((N,U)=>r.jsx("button",{type:"button",onClick:()=>J(N.prompt),className:"p-2.5 rounded-xl border border-border bg-bg-card hover:bg-bg-elevated hover:border-purple-500/40 text-xs transition-all flex items-start gap-2 text-left group",children:r.jsx("span",{className:"font-semibold text-text-primary group-hover:text-purple-300",children:N.label})},U))})]})]}),q.messages.map(N=>N.role==="user"?r.jsx("div",{className:"flex justify-end animate-fade-in",children:r.jsxs("div",{className:"max-w-[85%] sm:max-w-[75%] rounded-2xl rounded-tr-sm bg-purple-600 text-white p-3.5 shadow-md shadow-purple-600/10 space-y-1",children:[r.jsx("p",{className:"text-xs sm:text-sm font-sans",children:N.content}),r.jsx("p",{className:"text-[10px] text-purple-200 text-right",children:N.timestamp})]})},N.id):r.jsx("div",{className:"flex flex-col space-y-2 animate-fade-in max-w-[95%] sm:max-w-[90%]",children:r.jsxs("div",{className:"rounded-2xl rounded-tl-sm bg-bg-card border border-border/90 p-4 sm:p-5 space-y-3.5 shadow-sm",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pb-2.5 border-b border-border/60",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"p-1 rounded-md bg-purple-500/20 text-purple-400",children:r.jsx(Be,{size:14})}),r.jsx("span",{className:"text-xs font-bold font-mono text-purple-300",children:/EXECUTIVE VERDICT|Actionable Trade Setup|Rencana Trading/i.test(N.content)?"Damian Quantitative Digest":"Damian Quant Partner"}),N.bias&&r.jsx("span",{className:`px-2 py-0.5 rounded text-[11px] font-mono font-bold border ${Jh(N.bias)}`,children:N.bias})]}),r.jsxs("div",{className:"flex items-center gap-1.5",children:[N.isCached&&r.jsx("span",{className:"text-[10px] font-mono text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-1.5 py-0.5 rounded",children:"Hemat Token (Cache)"}),r.jsx("button",{type:"button",onClick:()=>E(N.id),className:"px-2 py-1 rounded text-[10px] border border-border text-text-secondary hover:text-purple-300 flex items-center gap-1 hover:bg-bg-elevated transition-colors",title:R[N.id]?"Tampilkan narasi teks lengkap":"Ciutkan narasi teks analisa",children:R[N.id]?r.jsxs(r.Fragment,{children:[r.jsx(jt,{size:11}),r.jsx("span",{children:"Buka Teks"})]}):r.jsxs(r.Fragment,{children:[r.jsx(Us,{size:11}),r.jsx("span",{children:"Ciutkan Teks"})]})}),r.jsx("button",{type:"button",onClick:()=>$(N.content,N.id),className:"px-2 py-1 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:"Salin Analisa Lengkap",children:C===N.id?r.jsxs(r.Fragment,{children:[r.jsx(rt,{size:11,className:"text-signal-long"}),r.jsx("span",{className:"text-signal-long",children:"Tersalin"})]}):r.jsxs(r.Fragment,{children:[r.jsx(es,{size:11}),r.jsx("span",{children:"Salin"})]})})]})]}),!R[N.id]&&r.jsx(Ga,{content:N.content}),r.jsx(Kh,{symbol:d,content:N.content,bias:N.bias,dataSnapshot:N.dataSnapshot,tradeLevels:B?.trade_levels,modelUsed:N.model}),N.dataSnapshot&&r.jsxs("div",{className:"pt-2 border-t border-border/50",children:[r.jsxs("button",{type:"button",onClick:()=>W(N.id),className:"text-[11px] text-text-secondary hover:text-purple-300 flex items-center gap-1 transition-colors",children:[r.jsx(ei,{size:11}),r.jsx("span",{children:L[N.id]?"Sembunyikan Telemetry Data Mentah":"Lihat Telemetry Data Mentah yang Dikirim ke AI"}),L[N.id]?r.jsx(Us,{size:12}):r.jsx(jt,{size:12})]}),L[N.id]&&r.jsxs("div",{className:"mt-2 p-3 rounded-xl bg-bg-elevated border border-border/80 text-[10px] font-mono grid grid-cols-2 sm:grid-cols-4 gap-2.5 animate-fade-in",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"MARK PRICE"}),r.jsx("span",{className:"text-text-primary font-bold",children:N.dataSnapshot.mark_price_str||`$${N.dataSnapshot.mark_price}`})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"MULTI-VENUE SPREAD"}),r.jsxs("span",{className:"text-text-primary",children:[N.dataSnapshot.triangulation_spread_pct.toFixed(4),"%"]})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"BINANCE FR"}),r.jsx("span",{className:"text-text-primary",children:N.dataSnapshot.binance_fr})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"BYBIT FR"}),r.jsx("span",{className:"text-text-primary",children:N.dataSnapshot.bybit_fr})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"OKX FR"}),r.jsx("span",{className:"text-text-primary",children:N.dataSnapshot.okx_fr})]}),N.dataSnapshot.bitget_fr&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"BITGET FR"}),r.jsx("span",{className:"text-text-primary",children:N.dataSnapshot.bitget_fr})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"HYPERLIQUID FR"}),r.jsx("span",{className:"text-text-primary",children:N.dataSnapshot.hyperliquid_fr})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"SPOT CVD"}),r.jsx("span",{className:"text-text-primary",children:N.dataSnapshot.spot_cvd})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"FUTURES CVD"}),r.jsx("span",{className:"text-text-primary",children:N.dataSnapshot.futures_cvd})]}),r.jsxs("div",{className:"col-span-2",children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"LIQUIDATION MAGNETS"}),r.jsxs("span",{className:"text-text-primary",children:[N.dataSnapshot.upper_magnet," / ",N.dataSnapshot.lower_magnet]})]}),r.jsxs("div",{className:"col-span-2",children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"ORDERBOOK PRESSURE"}),r.jsx("span",{className:"text-text-primary",children:N.dataSnapshot.resting_pressure})]}),N.dataSnapshot.lead_lag_spread_bps!==void 0&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"LEAD-LAG SPREAD"}),r.jsxs("span",{className:"text-cyan-300",children:[N.dataSnapshot.lead_lag_spread_bps.toFixed(1)," bps (",N.dataSnapshot.leading_exchange?.toUpperCase()||"BALANCED",")"]})]}),N.dataSnapshot.funding_countdown&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"SETTLEMENT"}),r.jsx("span",{className:N.dataSnapshot.is_settlement_imminent?"text-amber-400 font-bold":"text-text-primary",children:N.dataSnapshot.funding_countdown})]}),N.dataSnapshot.range_24h_pct!==void 0&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"24H RANGE"}),r.jsxs("span",{className:"text-text-primary",children:[N.dataSnapshot.range_24h_pct.toFixed(2),"% (",N.dataSnapshot.range_position_pct?.toFixed(0),"% pos)"]})]}),N.dataSnapshot.whale_buy_count!==void 0&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-muted block text-[9px]",children:"WHALE BLOCKS"}),r.jsxs("span",{className:"text-emerald-400",children:[N.dataSnapshot.whale_buy_count,"B / ",N.dataSnapshot.whale_sell_count,"S"]})]})]})]}),r.jsxs("div",{className:"flex items-center justify-between text-[10px] text-text-muted pt-1",children:[r.jsxs("span",{children:["Model: ",N.model||a.model]}),r.jsx("span",{children:N.timestamp})]})]})},N.id)),q.isLoading&&r.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-2xl bg-bg-card border border-purple-500/20 max-w-md animate-fade-in",children:[r.jsx("div",{className:"w-8 h-8 rounded-full border-2 border-purple-500/30 border-t-purple-500 animate-spin shrink-0"}),r.jsxs("div",{className:"space-y-1",children:[r.jsxs("p",{className:"text-xs font-bold text-text-primary flex items-center gap-1.5",children:[r.jsx(Fe,{size:13,className:"text-purple-400 animate-pulse"}),"Menganalisa Aliran Modal ",d,"..."]}),r.jsxs("p",{className:"text-[10px] text-text-muted",children:["Menyintesis data orderbook, likuidasi, Spot vs Futures CVD ke ",a.model,"..."]})]})]}),q.error&&!q.isLoading&&r.jsxs("div",{className:"p-3.5 rounded-xl bg-red-500/10 border border-red-500/30 flex items-start gap-2.5 text-xs text-red-200",children:[r.jsx(ar,{size:16,className:"text-red-400 shrink-0 mt-0.5"}),r.jsxs("div",{className:"space-y-1 flex-1",children:[r.jsx("p",{className:"font-bold text-red-300",children:"Gagal Mendapatkan Analisa AI"}),r.jsx("p",{className:"text-[11px] text-red-200/90",children:q.error}),r.jsxs("div",{className:"pt-1 flex items-center gap-2",children:[r.jsx("button",{onClick:()=>J(void 0,!0),className:"text-[10px] px-2 py-0.5 rounded bg-red-500/20 hover:bg-red-500/30 text-red-100 font-semibold border border-red-500/40",children:"Coba Lagi"}),r.jsx("button",{onClick:()=>k(!0),className:"text-[10px] text-purple-300 hover:underline",children:"Buka Pengaturan AI"})]})]})]}),r.jsx("div",{ref:F})]}),r.jsxs("div",{className:"p-3 sm:p-4 border-t border-border bg-bg-card/95 shrink-0 pb-16 md:pb-4",children:[q.messages.length>0&&r.jsx("div",{className:"flex items-center gap-1.5 overflow-x-auto no-scrollbar pb-2 mb-1",children:an.map((N,U)=>r.jsx("button",{type:"button",onClick:()=>J(N.prompt),disabled:q.isLoading,className:"px-2.5 py-1 rounded-lg text-[10px] font-medium bg-bg-elevated hover:bg-purple-600/20 hover:text-purple-300 border border-border text-text-secondary transition-all shrink-0 disabled:opacity-50",children:N.label},U))}),r.jsxs("form",{onSubmit:N=>{N.preventDefault(),J()},className:"flex items-center gap-2",children:[r.jsx("input",{type:"text",value:g,onChange:N=>S(N.target.value),placeholder:`Tanyakan analisa teknikal, validasi trap, atau scalping ke Damian untuk ${d}...`,disabled:q.isLoading,className:"flex-1 bg-bg-elevated border border-border focus:border-purple-500/60 rounded-xl px-3.5 py-2.5 text-xs sm:text-sm text-text-primary placeholder:text-text-muted focus:outline-none transition-colors"}),r.jsx(se,{type:"submit",variant:"primary",size:"md",loading:q.isLoading,disabled:q.isLoading||!g.trim(),icon:r.jsx(Vo,{size:14}),className:"bg-purple-600 hover:bg-purple-500 text-white rounded-xl px-4 py-2.5 shadow-sm shadow-purple-600/30 shrink-0",children:r.jsx("span",{className:"hidden xs:inline",children:"Kirim"})})]})]})]}),j&&r.jsx(y.Suspense,{fallback:null,children:r.jsx(Yh,{isOpen:j,onClose:()=>k(!1)})})]})}const Zh=[{id:"WICK_HUNT",label:"⚡ Jarum Wick Hunt",desc:"SL tersapu jarum tipis lalu harga langsung mantul balik"},{id:"FALSE_BREAKOUT",label:"🛑 False Breakout",desc:"Terjebak beli di pucuk resisten atau sell di dasar support"},{id:"BTC_DUMP",label:"📉 Market / BTC Drag",desc:"Terseret kejatuhan pasar global / dump mendadak Bitcoin"},{id:"TREND_REVERSAL",label:"🔄 Trend Reversal (HTF)",desc:"Struktur tren HTF (1H/4H) patah berbalik arah melawan posisi"},{id:"PREMATURE_ENTRY",label:"⚠️ Entry Prematur",desc:"Masuk sebelum candle konfirmasi / pullback selesai terbentuk"},{id:"OTHER",label:"📝 Alasan Lainnya",desc:"Penyebab teknis atau faktor pasar lainnya"}];function eu({onNavigateToAI:s,isActiveTab:e}){const[t,i]=y.useState([]),[n,a]=y.useState({total:0,hit_tp:0,hit_sl:0,pending:0,cancelled:0,completed:0,win_rate_pct:0,unaudited_sl_count:0}),[o,l]=y.useState([]),[c,d]=y.useState(!0),[h,u]=y.useState("ALL"),[m,x]=y.useState(""),[b,f]=y.useState(null),[v,p]=y.useState(""),[g,S]=y.useState("WICK_HUNT"),[j,k]=y.useState(""),[C,M]=y.useState(!1),[L,I]=y.useState({}),[R,T]=y.useState(null),[E,F]=y.useState(!1),[B,z]=y.useState(!1),[V,q]=y.useState(""),[J,oe]=y.useState(!1),{settings:$}=ci(),{toast:W}=ft(),N=y.useMemo(()=>{switch($.provider){case"gemini":return Ih;case"openai":return $h;case"groq":return[{id:"llama-3.3-70b-versatile",label:"Llama 3.3 70B Versatile (Recommended)"},{id:"deepseek-r1-distill-llama-70b",label:"DeepSeek R1 Distill Llama 70B"},{id:"llama-3.1-8b-instant",label:"Llama 3.1 8B Instant (Fast)"}];case"vikey":default:return zh}},[$.provider]);y.useEffect(()=>{$.model&&N.some(_=>_.id===$.model)?q($.model):N.length>0&&q(N[0].id)},[$.provider,$.model,N]);const U=async(_=!1)=>{_||d(!0);try{const[Q,Y,Z]=await Promise.all([Le.getEntries("ALL",100),Le.getStats(),Le.getMemory()]);i(Q.entries),a(Y),l(Z.memories)}catch(Q){_||W(Q.message||"Gagal memuat data Jurnal Trade","error")}finally{_||d(!1)}};y.useEffect(()=>{U(),$.model&&q($.model)},[]),y.useEffect(()=>{e&&U(!0)},[e]),y.useEffect(()=>{const _=Q=>{const Y=Q?.detail;Y&&Y.id?(i(Z=>Y.deleted_id?Z.filter(X=>X.id!==Y.deleted_id):Z.some(X=>X.id===Y.id)?Z.map(X=>X.id===Y.id?{...X,...Y}:X):[Y,...Z]),Le.getStats().then(a).catch(()=>{})):U(!0)};return window.addEventListener("journal-updated",_),()=>{window.removeEventListener("journal-updated",_)}},[]);const A=y.useMemo(()=>t.filter(_=>_.symbol.toLowerCase().includes(m.toLowerCase().trim())||_.bias.toLowerCase().includes(m.toLowerCase().trim())?h==="ALL"?!0:_.status===h:!1),[t,m,h]),ee=_=>{try{const Q=new Date(_).getTime(),Y=Date.now(),Z=Math.max(0,Math.floor((Y-Q)/1e3)),H=Math.floor(Z/3600),X=Math.floor(Z%3600/60);let ke=`${X} menit`;return H>0&&(ke=`${H} jam ${X} menit`),{seconds:Z,formatted:ke}}catch{return{seconds:0,formatted:"N/A"}}},xe=_=>{I(Q=>({...Q,[_]:!Q[_]}))},K=(_,Q)=>{f({entry:_,targetStatus:Q}),p(_.outcome_note||""),S(_.failure_tag||(Q==="HIT_SL"?"WICK_HUNT":"")),k(_.exit_price?String(_.exit_price):"")},te=async()=>{if(b){M(!0);try{const _=ee(b.entry.created_at),Q=j.trim()?parseFloat(j.trim()):void 0,Y=await Le.updateStatus(b.entry.id,b.targetStatus,v.trim()||void 0,b.targetStatus==="HIT_SL"?g||"OTHER":void 0,Q&&!isNaN(Q)?Q:void 0,_.seconds>0?_.seconds:void 0);i(H=>H.map(X=>X.id===b.entry.id?Y.entry:X)),a(Y.stats),W({HIT_TP:"🟢 Berhasil HIT TP! Selamat atas cuan Anda!",HIT_SL:"🔴 Terkena Stop Loss. Diagnosa & telemetri dicatat untuk evaluasi Damian.",CANCELLED:"⚪ Sinyal dibatalkan / Breakeven."}[b.targetStatus],"info"),f(null)}catch(_){W(_.message||"Gagal memperbarui status","error")}finally{M(!1)}}},be=async _=>{try{const Q=await Le.updateStatus(_.id,"PENDING");i(Y=>Y.map(Z=>Z.id===_.id?Q.entry:Z)),a(Q.stats),W(`[${_.symbol}] Status dikembalikan ke Sedang Berjalan (Pending)`,"info")}catch(Q){W(Q.message||"Gagal mengembalikan status","error")}},Se=_=>{T(_)},Ze=async()=>{if(!R)return;F(!0);const _=R.symbol,Q=R.id;try{await Le.deleteEntry(Q),i(Y=>Y.filter(Z=>Z.id!==Q)),T(null),W(`[${_}] Berhasil dihapus permanen dari Jurnal & Database.`,"info");try{const Y=await Le.getStats();a(Y)}catch{}}catch(Y){W(Y.message||"Gagal menghapus catatan trade","error")}finally{F(!1)}},ge=async()=>{if(!$.api_key||!$.api_key.trim()){W("API Key AI belum terpasang. Harap masukkan API Key Anda di Pengaturan AI Universal (ikon gear di navbar atas).","error");return}oe(!0);try{const _=await Le.synthesizeAudit({api_key:$.api_key,provider:$.provider,model:V||N[0]?.id,base_url:$.base_url,force:!0});W(_.message,"success"),z(!1),await U()}catch(_){W(_.message||"Gagal menjalankan audit memori Damian","error")}finally{oe(!1)}},we=_=>{switch(_){case"HIT_TP":return r.jsxs("span",{className:"px-2.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-emerald-500/15 border border-emerald-500/40 text-emerald-300 flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400"}),"HIT TP (CUAN)"]});case"HIT_SL":return r.jsxs("span",{className:"px-2.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-rose-500/15 border border-rose-500/40 text-rose-300 flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-rose-400"}),"HIT SL (RUGI)"]});case"CANCELLED":return r.jsx("span",{className:"px-2.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-gray-500/15 border border-gray-500/30 text-gray-400 flex items-center gap-1",children:"BATAL / BE"});default:return r.jsxs("span",{className:"px-2.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-amber-500/15 border border-amber-500/40 text-amber-300 flex items-center gap-1 animate-pulse",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400"}),"BERJALAN (PENDING)"]})}};return r.jsxs("div",{className:"flex-1 flex flex-col h-[calc(100vh-3.5rem)] overflow-y-auto custom-scrollbar bg-bg-primary select-none",children:[r.jsxs("div",{className:"max-w-6xl w-full mx-auto p-3 sm:p-5 space-y-4",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-2 border-b border-border/60",children:[r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.jsx("div",{className:"p-2 rounded-xl bg-purple-500/20 text-purple-300 border border-purple-500/30",children:r.jsx(Rr,{size:20})}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h2",{className:"text-base sm:text-lg font-bold text-text-primary font-mono tracking-tight",children:"Jurnal Trade Damian"}),r.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-purple-500/20 text-purple-300 border border-purple-500/30",children:"Continuous Learning"})]}),r.jsx("p",{className:"text-xs text-text-muted mt-0.5",children:"Konfirmasi hasil trade Anda. Damian belajar dari setiap Stop Loss untuk menyempurnakan analisa berikutnya."})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(se,{variant:"primary",size:"sm",onClick:()=>z(!0),icon:r.jsx(yt,{size:13}),className:`${n.unaudited_sl_count>=10?"bg-purple-600 hover:bg-purple-500 text-white shadow-lg shadow-purple-600/30 animate-pulse":"bg-purple-600/30 hover:bg-purple-600/50 text-purple-200 border border-purple-500/40"}`,children:[r.jsx("span",{children:"Audit Memori Damian"}),r.jsxs("span",{className:"px-1.5 py-0.2 rounded text-[10px] font-mono bg-bg-primary/60 font-bold ml-1",children:[n.unaudited_sl_count,"/10 SL"]})]}),r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>U(),loading:c,icon:r.jsx(Re,{size:13}),title:"Perbarui data jurnal"})]})]}),r.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5",children:[r.jsxs("div",{className:"p-3.5 rounded-xl bg-bg-card border border-border flex flex-col justify-between space-y-1 shadow-sm",children:[r.jsx("span",{className:"text-[10px] text-text-muted uppercase font-bold tracking-wider",children:"WIN RATE REALISTIS"}),r.jsx("div",{className:"text-xl sm:text-2xl font-bold font-mono text-emerald-400",children:n.completed>0?`${n.win_rate_pct}%`:"N/A"}),r.jsxs("span",{className:"text-[10px] text-text-muted",children:["Dari ",n.completed," trade selesai (",n.hit_tp," TP vs ",n.hit_sl," SL)"]})]}),r.jsxs("div",{className:"p-3.5 rounded-xl bg-emerald-500/10 border border-emerald-500/20 flex flex-col justify-between space-y-1 shadow-sm",children:[r.jsxs("div",{className:"flex items-center justify-between text-emerald-300",children:[r.jsx("span",{className:"text-[10px] uppercase font-bold tracking-wider",children:"TOTAL HIT TP"}),r.jsx(Ye,{size:14,className:"text-emerald-400"})]}),r.jsxs("div",{className:"text-xl sm:text-2xl font-bold font-mono text-emerald-300",children:[n.hit_tp," Trade"]}),r.jsx("span",{className:"text-[10px] text-emerald-300/80",children:"Selesai Take Profit"})]}),r.jsxs("div",{className:"p-3.5 rounded-xl bg-rose-500/10 border border-rose-500/20 flex flex-col justify-between space-y-1 shadow-sm",children:[r.jsxs("div",{className:"flex items-center justify-between text-rose-300",children:[r.jsx("span",{className:"text-[10px] uppercase font-bold tracking-wider",children:"TOTAL STOP LOSS"}),r.jsx(Tt,{size:14,className:"text-rose-400"})]}),r.jsxs("div",{className:"text-xl sm:text-2xl font-bold font-mono text-rose-300",children:[n.hit_sl," Trade"]}),r.jsxs("span",{className:"text-[10px] text-rose-300/80",children:[n.unaudited_sl_count," belum diaudit"]})]}),r.jsxs("div",{className:"p-3.5 rounded-xl bg-amber-500/10 border border-amber-500/20 flex flex-col justify-between space-y-1 shadow-sm",children:[r.jsxs("div",{className:"flex items-center justify-between text-amber-300",children:[r.jsx("span",{className:"text-[10px] uppercase font-bold tracking-wider",children:"SEDANG BERJALAN"}),r.jsx(Fe,{size:14,className:"text-amber-400"})]}),r.jsxs("div",{className:"text-xl sm:text-2xl font-bold font-mono text-amber-300",children:[n.pending," Trade"]}),r.jsx("span",{className:"text-[10px] text-amber-300/80",children:"Menunggu konfirmasi Anda"})]})]}),o.length>0?r.jsxs("div",{className:"p-4 rounded-2xl bg-gradient-to-r from-purple-950/40 via-bg-card to-purple-950/20 border border-purple-500/30 shadow-md space-y-2.5",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(yt,{size:16,className:"text-purple-400"}),r.jsxs("span",{className:"text-xs font-bold text-purple-200 font-mono",children:["Aturan Pengaman Emas Damian (Batch #",o[0].batch_index,")"]}),r.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40",children:"Aktif pada Analisa Damian"})]}),r.jsxs("span",{className:"text-[10px] text-text-muted font-mono hidden sm:inline",children:["Model Auditor: ",o[0].model_used]})]}),r.jsx("div",{className:"p-3 rounded-xl bg-bg-elevated/40 border border-border/80",children:r.jsx(Ga,{content:o[0].audit_summary})}),r.jsxs("p",{className:"text-[10px] text-purple-300 flex items-center gap-1",children:[r.jsx(Fe,{size:11,className:"text-purple-400"}),"Aturan ini otomatis disuntikkan ke otak Damian setiap kali Anda meminta analisa baru agar tidak mengulangi kesalahan sebelumnya."]})]}):r.jsx("div",{className:"p-3.5 rounded-xl bg-purple-500/10 border border-purple-500/20 text-xs text-purple-200 flex items-center justify-between gap-3",children:r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.jsx(yt,{size:16,className:"text-purple-400 shrink-0"}),r.jsxs("span",{children:[r.jsx("strong",{children:"Siklus Pembelajaran Mandiri:"})," Kumpulkan 10 trade yang terkena Stop Loss di bawah ini, lalu jalankan ",r.jsx("strong",{children:"Audit Memori Damian"})," untuk merumuskan aturan pengaman baru secara otomatis!"]})]})}),r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2.5 pt-2",children:[r.jsx("div",{className:"flex items-center gap-1 overflow-x-auto no-scrollbar",children:[{id:"ALL",label:`Semua (${n.total})`},{id:"PENDING",label:`Pending (${n.pending})`},{id:"HIT_TP",label:`Hit TP (${n.hit_tp})`},{id:"HIT_SL",label:`Hit SL (${n.hit_sl})`},{id:"CANCELLED",label:`Batal (${n.cancelled})`}].map(_=>r.jsx("button",{type:"button",onClick:()=>u(_.id),className:`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all shrink-0 ${h===_.id?"bg-purple-600 text-white shadow-sm":"bg-bg-elevated/70 text-text-secondary hover:text-text-primary"}`,children:_.label},_.id))}),r.jsxs("div",{className:"relative w-full sm:w-60",children:[r.jsx(Zs,{size:13,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-text-muted"}),r.jsx("input",{type:"text",value:m,onChange:_=>x(_.target.value),placeholder:"Cari pair (e.g. BTC, SOL)...",className:"w-full bg-bg-elevated border border-border rounded-lg pl-8 pr-2.5 py-1.5 text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500/50"})]})]}),c?r.jsxs("div",{className:"py-12 flex flex-col items-center justify-center space-y-2 text-text-muted",children:[r.jsx(Re,{size:24,className:"animate-spin text-purple-400"}),r.jsx("p",{className:"text-xs",children:"Memuat data Jurnal Trade..."})]}):A.length===0?r.jsxs("div",{className:"py-12 border border-dashed border-border rounded-2xl flex flex-col items-center justify-center text-center p-6 space-y-2",children:[r.jsx(Rr,{size:32,className:"text-text-muted"}),r.jsx("p",{className:"text-sm font-bold text-text-primary",children:"Belum Ada Catatan Trade"}),r.jsxs("p",{className:"text-xs text-text-muted max-w-sm",children:["Gunakan Damian untuk menganalisa koin, lalu klik tombol ",r.jsx("strong",{children:'"📌 Catat ke Jurnal"'})," pada Card Kesimpulan untuk memantau performanya di sini."]})]}):r.jsx("div",{className:"space-y-3",children:A.map(_=>r.jsxs("div",{className:"p-4 rounded-xl bg-bg-card border border-border hover:border-border-hover transition-all space-y-3 shadow-sm group",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pb-2.5 border-b border-border/50",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("span",{className:"text-sm font-bold font-mono text-text-primary",children:_.symbol}),r.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-mono font-bold border ${_.bias.includes("LONG")||_.bias.includes("BUY")?"bg-emerald-500/15 text-emerald-300 border-emerald-500/30":_.bias.includes("SHORT")||_.bias.includes("SELL")?"bg-rose-500/15 text-rose-300 border-rose-500/30":"bg-amber-500/15 text-amber-300 border-amber-500/30"}`,children:_.bias}),we(_.status),_.failure_tag&&r.jsxs("span",{className:"px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-rose-950/60 border border-rose-500/40 text-rose-300 flex items-center gap-1",children:[_.failure_tag==="WICK_HUNT"&&"⚡ Jarum Wick Hunt",_.failure_tag==="FALSE_BREAKOUT"&&"🛑 False Breakout",_.failure_tag==="BTC_DUMP"&&"📉 Market / BTC Drag",_.failure_tag==="TREND_REVERSAL"&&"🔄 Trend Reversal",_.failure_tag==="PREMATURE_ENTRY"&&"⚠️ Entry Prematur",_.failure_tag==="OTHER"&&"📝 Alasan Lainnya",!["WICK_HUNT","FALSE_BREAKOUT","BTC_DUMP","TREND_REVERSAL","PREMATURE_ENTRY","OTHER"].includes(_.failure_tag)&&_.failure_tag]}),_.holding_duration_seconds&&_.holding_duration_seconds>0&&r.jsxs("span",{className:"text-[10px] font-mono text-purple-300/90 flex items-center gap-1 bg-purple-500/10 px-1.5 py-0.5 rounded border border-purple-500/20",children:[r.jsx(Fs,{size:10,className:"text-purple-400"}),Math.floor(_.holding_duration_seconds/3600)>0?`${Math.floor(_.holding_duration_seconds/3600)}j ${Math.floor(_.holding_duration_seconds%3600/60)}m`:`${Math.floor(_.holding_duration_seconds/60)}m`]}),_.exit_price&&r.jsxs("span",{className:"text-[10px] font-mono text-emerald-300/90 bg-emerald-500/10 px-1.5 py-0.5 rounded border border-emerald-500/20",children:["Exit: $",_.exit_price.toLocaleString()]}),_.audited&&r.jsx("span",{className:"text-[9px] font-mono px-1.5 py-0.2 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30",children:"Diaudit"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-[10px] text-text-muted font-mono",children:new Date(_.created_at).toLocaleString("id-ID",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"})}),s&&r.jsx("button",{type:"button",onClick:()=>s(_.symbol),className:"p-1 rounded text-text-muted hover:text-purple-300 transition-colors",title:"Buka pair ini di Damian",children:r.jsx(Be,{size:13})}),r.jsx("button",{type:"button",onClick:()=>Se(_),className:"p-1 rounded text-text-muted hover:text-rose-400 transition-colors",title:"Hapus dari jurnal",children:r.jsx(Qt,{size:13})})]})]}),r.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs font-mono",children:[r.jsxs("div",{className:"p-2 rounded-lg bg-bg-elevated/70 border border-border",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"ENTRY ZONE"}),r.jsx("span",{className:"text-text-primary font-bold",children:_.entry_zone||"N/A"})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-rose-500/10 border border-rose-500/20",children:[r.jsx("span",{className:"text-[9px] text-rose-300 block",children:"STOP LOSS"}),r.jsx("span",{className:"text-rose-400 font-bold",children:_.stop_loss||"N/A"})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-emerald-500/10 border border-emerald-500/20",children:[r.jsx("span",{className:"text-[9px] text-emerald-300 block",children:"TARGET TP"}),r.jsx("span",{className:"text-emerald-400 font-bold",children:_.take_profit||"N/A"})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-purple-500/10 border border-purple-500/20",children:[r.jsx("span",{className:"text-[9px] text-purple-300 block",children:"R:R & LEV"}),r.jsxs("span",{className:"text-purple-300 font-bold",children:[_.risk_reward||"1:2"," • ",_.leverage||"2-3x"]})]})]}),_.summary_tldr&&r.jsxs("p",{className:"text-xs text-text-secondary leading-relaxed bg-bg-elevated/40 p-2.5 rounded-lg border border-border/60",children:[r.jsx("span",{className:"font-semibold text-text-primary",children:"💡 Intisari: "}),_.summary_tldr]}),_.outcome_note&&r.jsxs("p",{className:"text-[11px] text-text-muted italic bg-bg-elevated/60 px-2.5 py-1.5 rounded border border-border/80",children:["📝 Catatan Hasil: ",_.outcome_note]}),_.snapshot_data&&r.jsxs("div",{className:"pt-1",children:[r.jsxs("button",{type:"button",onClick:()=>xe(_.id),className:"w-full flex items-center justify-between px-3 py-2 rounded-lg bg-purple-950/20 hover:bg-purple-950/40 border border-purple-500/20 hover:border-purple-500/40 text-xs font-mono text-purple-300 transition-all shadow-sm",children:[r.jsxs("span",{className:"flex items-center gap-1.5 font-bold",children:[r.jsx(ei,{size:13,className:"text-purple-400"}),r.jsx("span",{children:"Data Pasar Saat Rekomendasi (Telemetri Kuantitatif)"})]}),r.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-text-muted",children:[L[_.id]?"Sembunyikan":"Buka Sidik Jari Pasar",L[_.id]?r.jsx(Us,{size:13}):r.jsx(jt,{size:13})]})]}),L[_.id]&&r.jsxs("div",{className:"mt-2 p-3.5 rounded-xl bg-bg-elevated/70 border border-purple-500/20 space-y-3 animate-fade-in text-xs font-mono",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 pb-2",children:[r.jsxs("span",{className:"text-[10px] uppercase font-bold tracking-wider text-purple-300 flex items-center gap-1",children:[r.jsx(nt,{size:12,className:"text-purple-400"}),"Sidik Jari Pasar Mikrostruktur Pada Saat Entry"]}),r.jsxs("span",{className:"text-[10px] text-text-muted",children:["Model: ",_.model_used||"Damian Quant Engine"]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2 text-[11px]",children:[r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"MARK PRICE & 24H POS"}),r.jsx("div",{className:"font-bold text-text-primary",children:_.snapshot_data.mark_price_str||(_.snapshot_data.mark_price?`$${_.snapshot_data.mark_price}`:"N/A")}),r.jsxs("div",{className:"text-[10px] text-purple-300",children:["Posisi: ",_.snapshot_data.range_position_pct??"50","% (",_.snapshot_data.range_zone_label||"Equilibrium",")"]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"ORDER FLOW CVD"}),r.jsx("div",{className:"font-bold text-text-primary",children:_.snapshot_data.cvd_verdict||"Netral"}),r.jsxs("div",{className:"text-[10px] text-text-secondary truncate",children:["Spot: ",_.snapshot_data.spot_cvd||"0"," | Fut: ",_.snapshot_data.futures_cvd||"0"]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"FUNDING RATE 8H & APR"}),r.jsxs("div",{className:`font-bold ${(_.snapshot_data.avg_fr_8h_pct||0)<0?"text-emerald-400":"text-rose-400"}`,children:[_.snapshot_data.avg_fr_8h_pct!==void 0?`${_.snapshot_data.avg_fr_8h_pct}%`:"N/A"," ",r.jsxs("span",{className:"text-[9px] font-normal text-text-muted",children:["(",_.snapshot_data.annualized_apr_pct!==void 0?`${_.snapshot_data.annualized_apr_pct}% APR`:"",")"]})]}),r.jsxs("div",{className:"text-[10px] text-text-muted",children:["Settlement: ",_.snapshot_data.funding_countdown||"N/A"]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"ORDERBOOK SKEW (TOP 20)"}),r.jsxs("div",{className:"font-bold text-text-primary",children:[_.snapshot_data.resting_pressure||"Neutral"," ",r.jsxs("span",{className:"text-[9px] font-normal text-text-muted",children:["(",_.snapshot_data.depth_ratio?`${_.snapshot_data.depth_ratio}x`:"1.0x",")"]})]}),r.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:["Bids $",Number(_.snapshot_data.bid_depth_usd||0).toLocaleString()," vs Asks $",Number(_.snapshot_data.ask_depth_usd||0).toLocaleString()]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"STRUKTUR MULTI-TIMEFRAME"}),r.jsx("div",{className:"flex items-center gap-1 flex-wrap pt-0.5",children:["15m","1h","4h","1d"].map(Q=>{const Y=_.snapshot_data?.market_structure?.[Q]||"neutral",Z=Y.toLowerCase().includes("bull")||Y.toLowerCase().includes("uptrend"),H=Y.toLowerCase().includes("bear")||Y.toLowerCase().includes("downtrend");return r.jsxs("span",{className:`px-1 py-0.2 rounded text-[9px] font-bold ${Z?"bg-emerald-500/20 text-emerald-300":H?"bg-rose-500/20 text-rose-300":"bg-gray-500/20 text-gray-300"}`,children:[Q.toUpperCase(),":",Y.substring(0,4).toUpperCase()]},Q)})})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"SQUEEZE & BREAKOUT RADAR"}),r.jsxs("div",{className:"font-bold text-purple-300",children:[_.snapshot_data.squeeze_intensity||"NORMAL"," ",r.jsxs("span",{className:"text-[9px] font-normal text-text-muted",children:["(",_.snapshot_data.compression_ratio?`CR: ${_.snapshot_data.compression_ratio}`:"",")"]})]}),r.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:["Radar: ",_.snapshot_data.breakout_radar?.radar_label||"NORMAL"]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"WHALES & LEAD-LAG"}),r.jsxs("div",{className:"font-bold text-text-primary",children:["Taker Buy: ",_.snapshot_data.taker_buy_pct??50,"%"]}),r.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:["Pemimpin: ",_.snapshot_data.leading_exchange||"N/A"," ",_.snapshot_data.lead_lag_spread_bps?`(+${_.snapshot_data.lead_lag_spread_bps} bps)`:""]})]}),r.jsxs("div",{className:"p-2 rounded-lg bg-bg-card border border-border space-y-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted block",children:"KEYAKINAN & REZIM PASAR"}),r.jsxs("div",{className:"font-bold text-purple-200",children:["Conviction: ",_.snapshot_data.conviction??"N/A","/10"," ",r.jsxs("span",{className:"text-[9px] font-normal text-text-muted",children:["(",_.snapshot_data.confluence_pct??"N/A","%)"]})]}),r.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:["Rezim: ",_.snapshot_data.global_regime||"NEUTRAL"]})]})]}),_.invalidation&&r.jsxs("div",{className:"p-2 rounded-lg bg-rose-500/10 border border-rose-500/20 text-[10px] text-rose-200 flex items-start gap-1.5",children:[r.jsx(Tt,{size:12,className:"text-rose-400 shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("strong",{className:"text-rose-300",children:"Syarat Pembatalan (Invalidation Rule):"})," ",_.invalidation]})]}),_.snapshot_data.warnings&&_.snapshot_data.warnings.length>0&&r.jsxs("div",{className:"p-2 rounded-lg bg-amber-500/10 border border-amber-500/20 text-[10px] text-amber-200 flex items-start gap-1.5",children:[r.jsx(ve,{size:12,className:"text-amber-400 shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("strong",{className:"text-amber-300",children:"Peringatan Terdeteksi Saat Entry:"})," ",_.snapshot_data.warnings.join(" • ")]})]})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-2 border-t border-border/50",children:[r.jsx("span",{className:"text-[11px] text-text-muted font-medium",children:_.status==="PENDING"?"Konfirmasi hasil trade Anda di bursa:":r.jsxs("span",{children:["Status: ",r.jsx("strong",{className:"text-text-primary",children:_.status==="HIT_TP"?"🟢 Selesai Hit TP":_.status==="HIT_SL"?"🔴 Selesai Hit SL":"⚪ Sinyal Batal / BE"})," ",r.jsx("span",{className:"text-text-muted text-[10px]",children:"(klik untuk ubah):"})]})}),r.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>K(_,"HIT_TP"),className:`text-xs py-1 px-2.5 transition-all ${_.status==="HIT_TP"?"bg-emerald-500/30 text-emerald-200 border-emerald-500 font-bold shadow-sm shadow-emerald-950/40":"bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-300 border border-emerald-500/30"}`,icon:r.jsx(rt,{size:12}),children:"Hit TP"}),r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>K(_,"HIT_SL"),className:`text-xs py-1 px-2.5 transition-all ${_.status==="HIT_SL"?"bg-rose-500/30 text-rose-200 border-rose-500 font-bold shadow-sm shadow-rose-950/40":"bg-rose-500/10 hover:bg-rose-500/20 text-rose-300 border border-rose-500/30"}`,icon:r.jsx(Ct,{size:12}),children:"Hit SL"}),r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>K(_,"CANCELLED"),className:`text-xs py-1 px-2.5 transition-all ${_.status==="CANCELLED"?"bg-gray-500/30 text-gray-200 border-gray-400 font-bold shadow-sm":"bg-gray-500/10 hover:bg-gray-500/20 text-gray-300 border border-gray-500/30"}`,children:"Batal"}),_.status!=="PENDING"&&r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>be(_),className:"bg-amber-500/15 hover:bg-amber-500/25 text-amber-300 border border-amber-500/30 text-xs py-1 px-2 transition-all",title:"Kembalikan ke status Sedang Berjalan (Pending)",children:"Reset ke Pending"})]})]})]},_.id))})]}),b&&r.jsx(Is,{isOpen:!!b,onClose:()=>f(null),title:`Konfirmasi Hasil Trade: ${b.entry.symbol}`,size:b.targetStatus==="HIT_SL"?"md":"sm",children:r.jsxs("div",{className:"space-y-3.5",children:[r.jsxs("div",{className:"p-3 rounded-lg bg-bg-elevated border border-border text-xs space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-text-muted",children:"Pair & Bias:"}),r.jsxs("span",{className:"font-bold text-text-primary",children:[b.entry.symbol," (",b.entry.bias,")"]})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-text-muted",children:"Target Status:"}),r.jsx("span",{className:`font-bold ${b.targetStatus==="HIT_TP"?"text-emerald-400":b.targetStatus==="HIT_SL"?"text-rose-400":"text-gray-400"}`,children:b.targetStatus})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-text-muted",children:"Durasi Posisi Bertahan:"}),r.jsxs("span",{className:"font-bold font-mono text-purple-300 flex items-center gap-1",children:[r.jsx(Fs,{size:11,className:"text-purple-400"}),ee(b.entry.created_at).formatted]})]})]}),b.targetStatus==="HIT_SL"&&r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"block text-xs font-semibold text-rose-300",children:"⚡ Diagnosis Penyebab Stop Loss (Wajib untuk Pembelajaran Damian):"}),r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-1.5",children:Zh.map(_=>r.jsxs("button",{type:"button",onClick:()=>S(_.id),className:`p-2 rounded-lg text-left border transition-all ${g===_.id?"bg-rose-500/20 border-rose-500 text-rose-200 font-bold shadow-sm":"bg-bg-elevated/60 border-border/80 text-text-secondary hover:text-text-primary hover:border-border-hover"}`,children:[r.jsx("span",{className:"block font-mono text-[11px] font-bold",children:_.label}),r.jsx("span",{className:"text-[9px] text-text-muted block mt-0.5 line-clamp-1",children:_.desc})]},_.id))})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-xs font-semibold text-text-secondary mb-1",children:["Harga Exit (",b.targetStatus==="HIT_SL"?"SL Hit":"TP Hit",") — Opsional"]}),r.jsx("input",{type:"number",step:"any",value:j,onChange:_=>k(_.target.value),placeholder:b.targetStatus==="HIT_SL"?"e.g. 0.0868":"e.g. 0.1026",className:"w-full px-2.5 py-1.5 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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs font-semibold text-text-secondary mb-1",children:"Level Invalidation Terpasang"}),r.jsx("div",{className:"px-2.5 py-1.5 rounded-lg bg-bg-elevated/50 border border-border text-xs text-text-muted font-mono truncate h-[34px] flex items-center",children:b.entry.stop_loss||"N/A"})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs font-semibold text-text-secondary mb-1",children:"Catatan Evaluasi Pribadi / Catatan Post-Mortem (Opsional)"}),r.jsx("textarea",{value:v,onChange:_=>p(_.target.value),placeholder:"Contoh: Kena wick hunt pas settlement bursa jam 19:00, candle 1H langsung mantul kembali ke atas...",rows:2,className:"w-full p-2.5 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500"})]}),r.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2 border-t border-border",children:[r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>f(null),disabled:C,children:"Batal"}),r.jsx(se,{variant:"primary",size:"sm",onClick:te,loading:C,className:`${b.targetStatus==="HIT_TP"?"bg-emerald-600 hover:bg-emerald-500 text-white":b.targetStatus==="HIT_SL"?"bg-rose-600 hover:bg-rose-500 text-white":"bg-purple-600 hover:bg-purple-500 text-white"}`,children:"Konfirmasi Simpan"})]})]})}),B&&r.jsx(Is,{isOpen:B,onClose:()=>z(!1),title:"Audit Memori Pembelajaran Damian",size:"md",children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"p-3 rounded-xl bg-purple-500/10 border border-purple-500/20 text-xs text-purple-200 flex items-start gap-2.5",children:[r.jsx(yt,{size:18,className:"text-purple-400 shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("span",{className:"font-bold text-purple-100 block mb-0.5",children:"Root Cause Analysis (RCA) 10 Trade Gagal"}),"Damian akan menganalisa persamaan kondisi pasar pada trade yang terkena Stop Loss dan menyusun 3–4 Aturan Pengaman Emas agar tidak terjebak di pola yang sama pada analisa selanjutnya."]})]}),r.jsxs("div",{className:"p-3 rounded-xl bg-bg-elevated border border-border text-xs space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-text-muted",children:"Trade Stop Loss Tersedia:"}),r.jsxs("span",{className:"font-bold font-mono text-rose-400",children:[n.unaudited_sl_count," Trade"]})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-text-muted",children:"Target Audit Batch:"}),r.jsx("span",{className:"font-bold font-mono text-purple-300",children:"Maksimal 10 Trade per Batch"})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-1",children:[r.jsx("label",{className:"text-xs font-semibold text-text-secondary",children:"Model AI untuk Audit"}),r.jsxs("span",{className:"text-[10px] font-mono px-2 py-0.5 rounded bg-purple-500/15 border border-purple-500/30 text-purple-300 font-bold uppercase",children:["Provider: ",$.provider]})]}),r.jsx("select",{value:V,onChange:_=>q(_.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:N.map(_=>r.jsxs("option",{value:_.id,children:[_.label," (",_.id,")"]},_.id))})]}),r.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2 border-t border-border",children:[r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>z(!1),disabled:J,children:"Tutup"}),r.jsx(se,{variant:"primary",size:"sm",onClick:ge,loading:J,disabled:n.unaudited_sl_count===0,icon:r.jsx(yt,{size:13}),className:"bg-purple-600 hover:bg-purple-500 text-white",children:J?"Menganalisa Pola Kesalahan...":"Sintesis Golden Rules Sekarang"})]})]})}),R&&r.jsx(Is,{isOpen:!!R,onClose:()=>!E&&T(null),title:`Hapus Trade: ${R.symbol}`,size:"sm",children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"p-3.5 rounded-xl bg-rose-500/10 border border-rose-500/25 text-xs text-rose-200 flex items-start gap-3",children:[r.jsx("div",{className:"p-2 rounded-lg bg-rose-500/20 text-rose-400 shrink-0",children:r.jsx(Qt,{size:18})}),r.jsxs("div",{className:"space-y-1",children:[r.jsx("span",{className:"font-bold text-rose-100 block text-sm",children:"Konfirmasi Hapus Permanen"}),r.jsxs("p",{className:"text-rose-200/90 leading-relaxed",children:["Apakah Anda yakin ingin menghapus catatan trade ",r.jsx("strong",{children:R.symbol})," (",R.bias,")?"]}),r.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:["⚠️ Data ini akan ",r.jsx("strong",{children:"dihapus permanen dari database"})," dan statistik Win Rate akan langsung dikalkulasi ulang."]})]})]}),r.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2 border-t border-border",children:[r.jsx(se,{variant:"ghost",size:"sm",onClick:()=>T(null),disabled:E,children:"Batal"}),r.jsx(se,{variant:"primary",size:"sm",onClick:Ze,loading:E,className:"bg-rose-600 hover:bg-rose-500 text-white border border-rose-500/40",icon:r.jsx(Qt,{size:13}),children:"Ya, Hapus dari Database"})]})]})})]})}const Xi={getCandles:async(s,e="15m",t=150,i)=>{const n={timeframe:e,limit:t};return i&&i!=="auto"&&(n.exchange=i),(await ie.get(`/api/market/${s}/candles`,{params:n})).data},getMultiStream:async s=>(await ie.get(`/api/market/${s}/multi-stream`)).data,getFundingHistory:async(s,e=30)=>(await ie.get(`/api/market/${s}/funding-history`,{params:{limit:e}})).data};function tu({symbol:s,timeframe:e,exchange:t="auto",enabled:i=!0}){const[n,a]=y.useState([]),[o,l]=y.useState(0),[c,d]=y.useState(null),[h,u]=y.useState(!1),m=y.useRef(null),x=y.useRef(null),b=y.useRef(!0);y.useEffect(()=>{a([]),l(0),d(null)},[s,e,t]);const{data:f,isLoading:v,refetch:p,error:g}=Zt({queryKey:["chartCandles",s,e,t],queryFn:()=>Xi.getCandles(s,e,180,t),enabled:i&&!!s,staleTime:1e4,gcTime:6e4,refetchInterval:h?!1:5e3});y.useEffect(()=>{if(f?.candles){const k=(f.symbol||"").toUpperCase().replace("/","").replace("-",""),C=(s||"").toUpperCase().replace("/","").replace("-","");(!k||k===C)&&(a(f.candles),f.current_price&&f.current_price>0&&l(f.current_price))}},[f,s]);const{data:S}=Zt({queryKey:["multiStream",s],queryFn:()=>Xi.getMultiStream(s),enabled:i&&!!s,refetchInterval:h?1e4:3e3});y.useEffect(()=>{S&&(d(S),S.ref_price&&l(k=>k>0?k:S.ref_price||0))},[S]);const j=y.useCallback(()=>{if(!i||!s)return;const k=vd(s);if(k)try{m.current&&m.current.close();const C=new WebSocket(k);m.current=C,C.onopen=()=>{u(!0)},C.onmessage=M=>{try{const L=JSON.parse(M.data);if(L.type==="chart_tick"){const I=(L.symbol||"").toUpperCase().replace("/","").replace("-",""),R=(s||"").toUpperCase().replace("/","").replace("-","");if(I&&R&&I!==R)return;const T=Number(L.price);if(!T||isNaN(T)||T<=0)return;l(T),a(E=>{if(!E||E.length===0)return E;const F={...E[E.length-1]};if(F.close>0){const q=T/F.close;if(q<.2||q>5)return E}const B=L.time||Math.floor(Date.now()/1e3);let z=900;e==="1m"?z=60:e==="3m"?z=180:e==="5m"?z=300:e==="30m"?z=1800:e==="1h"?z=3600:e==="4h"?z=14400:e==="1d"&&(z=86400);const V=Math.floor(B/z)*z;if(F.time>=V)return F.close=T,F.high=Math.max(F.high,T),F.low=Math.min(F.low,T),[...E.slice(0,-1),F];{const q={time:V,open:T,high:T,low:T,close:T,volume:0,delta:0,cvd:F.cvd||0};return[...E,q]}})}L.exchanges&&d(I=>{if(!I)return I;const R={...I};return L.exchanges.binance&&R.exchanges?.binance&&(R.exchanges.binance.mark_price=L.exchanges.binance),L.exchanges.bybit&&R.exchanges?.bybit&&(R.exchanges.bybit.mark_price=L.exchanges.bybit),R})}catch{}},C.onclose=()=>{u(!1),b.current&&(x.current=setTimeout(()=>{b.current&&j()},3e3))},C.onerror=()=>{u(!1)}}catch{u(!1)}},[i,s,e]);return y.useEffect(()=>(b.current=!0,j(),()=>{b.current=!1,x.current&&clearTimeout(x.current),m.current&&(m.current.onclose=null,m.current.close(),m.current=null)}),[j]),{candles:n,currentPrice:o,multiStream:c,isAggregated:f?.is_aggregated??!1,exchangesIncluded:f?.exchanges_included??["binance"],summary:f?.summary,isLoading:v,isWsConnected:h,refetchCandles:p,error:g?g.message:null}}function re(s){var e=s.width,t=s.height;if(e<0)throw new Error("Negative width is not allowed for Size");if(t<0)throw new Error("Negative height is not allowed for Size");return{width:e,height:t}}function it(s,e){return s.width===e.width&&s.height===e.height}var su=function(){function s(e){var t=this;this._resolutionListener=function(){return t._onResolutionChanged()},this._resolutionMediaQueryList=null,this._observers=[],this._window=e,this._installResolutionListener()}return s.prototype.dispose=function(){this._uninstallResolutionListener(),this._window=null},Object.defineProperty(s.prototype,"value",{get:function(){return this._window.devicePixelRatio},enumerable:!1,configurable:!0}),s.prototype.subscribe=function(e){var t=this,i={next:e};return this._observers.push(i),{unsubscribe:function(){t._observers=t._observers.filter(function(n){return n!==i})}}},s.prototype._installResolutionListener=function(){if(this._resolutionMediaQueryList!==null)throw new Error("Resolution listener is already installed");var e=this._window.devicePixelRatio;this._resolutionMediaQueryList=this._window.matchMedia("all and (resolution: ".concat(e,"dppx)")),this._resolutionMediaQueryList.addListener(this._resolutionListener)},s.prototype._uninstallResolutionListener=function(){this._resolutionMediaQueryList!==null&&(this._resolutionMediaQueryList.removeListener(this._resolutionListener),this._resolutionMediaQueryList=null)},s.prototype._reinstallResolutionListener=function(){this._uninstallResolutionListener(),this._installResolutionListener()},s.prototype._onResolutionChanged=function(){var e=this;this._observers.forEach(function(t){return t.next(e._window.devicePixelRatio)}),this._reinstallResolutionListener()},s}();function iu(s){return new su(s)}var ru=function(){function s(e,t,i){var n;this._canvasElement=null,this._bitmapSizeChangedListeners=[],this._suggestedBitmapSize=null,this._suggestedBitmapSizeChangedListeners=[],this._devicePixelRatioObservable=null,this._canvasElementResizeObserver=null,this._canvasElement=e,this._canvasElementClientSize=re({width:this._canvasElement.clientWidth,height:this._canvasElement.clientHeight}),this._transformBitmapSize=t??function(a){return a},this._allowResizeObserver=(n=i?.allowResizeObserver)!==null&&n!==void 0?n:!0,this._chooseAndInitObserver()}return s.prototype.dispose=function(){var e,t;if(this._canvasElement===null)throw new Error("Object is disposed");(e=this._canvasElementResizeObserver)===null||e===void 0||e.disconnect(),this._canvasElementResizeObserver=null,(t=this._devicePixelRatioObservable)===null||t===void 0||t.dispose(),this._devicePixelRatioObservable=null,this._suggestedBitmapSizeChangedListeners.length=0,this._bitmapSizeChangedListeners.length=0,this._canvasElement=null},Object.defineProperty(s.prototype,"canvasElement",{get:function(){if(this._canvasElement===null)throw new Error("Object is disposed");return this._canvasElement},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"canvasElementClientSize",{get:function(){return this._canvasElementClientSize},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"bitmapSize",{get:function(){return re({width:this.canvasElement.width,height:this.canvasElement.height})},enumerable:!1,configurable:!0}),s.prototype.resizeCanvasElement=function(e){this._canvasElementClientSize=re(e),this.canvasElement.style.width="".concat(this._canvasElementClientSize.width,"px"),this.canvasElement.style.height="".concat(this._canvasElementClientSize.height,"px"),this._invalidateBitmapSize()},s.prototype.subscribeBitmapSizeChanged=function(e){this._bitmapSizeChangedListeners.push(e)},s.prototype.unsubscribeBitmapSizeChanged=function(e){this._bitmapSizeChangedListeners=this._bitmapSizeChangedListeners.filter(function(t){return t!==e})},Object.defineProperty(s.prototype,"suggestedBitmapSize",{get:function(){return this._suggestedBitmapSize},enumerable:!1,configurable:!0}),s.prototype.subscribeSuggestedBitmapSizeChanged=function(e){this._suggestedBitmapSizeChangedListeners.push(e)},s.prototype.unsubscribeSuggestedBitmapSizeChanged=function(e){this._suggestedBitmapSizeChangedListeners=this._suggestedBitmapSizeChangedListeners.filter(function(t){return t!==e})},s.prototype.applySuggestedBitmapSize=function(){if(this._suggestedBitmapSize!==null){var e=this._suggestedBitmapSize;this._suggestedBitmapSize=null,this._resizeBitmap(e),this._emitSuggestedBitmapSizeChanged(e,this._suggestedBitmapSize)}},s.prototype._resizeBitmap=function(e){var t=this.bitmapSize;it(t,e)||(this.canvasElement.width=e.width,this.canvasElement.height=e.height,this._emitBitmapSizeChanged(t,e))},s.prototype._emitBitmapSizeChanged=function(e,t){var i=this;this._bitmapSizeChangedListeners.forEach(function(n){return n.call(i,e,t)})},s.prototype._suggestNewBitmapSize=function(e){var t=this._suggestedBitmapSize,i=re(this._transformBitmapSize(e,this._canvasElementClientSize)),n=it(this.bitmapSize,i)?null:i;t===null&&n===null||t!==null&&n!==null&&it(t,n)||(this._suggestedBitmapSize=n,this._emitSuggestedBitmapSizeChanged(t,n))},s.prototype._emitSuggestedBitmapSizeChanged=function(e,t){var i=this;this._suggestedBitmapSizeChangedListeners.forEach(function(n){return n.call(i,e,t)})},s.prototype._chooseAndInitObserver=function(){var e=this;if(!this._allowResizeObserver){this._initDevicePixelRatioObservable();return}au().then(function(t){return t?e._initResizeObserver():e._initDevicePixelRatioObservable()})},s.prototype._initDevicePixelRatioObservable=function(){var e=this;if(this._canvasElement!==null){var t=on(this._canvasElement);if(t===null)throw new Error("No window is associated with the canvas");this._devicePixelRatioObservable=iu(t),this._devicePixelRatioObservable.subscribe(function(){return e._invalidateBitmapSize()}),this._invalidateBitmapSize()}},s.prototype._invalidateBitmapSize=function(){var e,t;if(this._canvasElement!==null){var i=on(this._canvasElement);if(i!==null){var n=(t=(e=this._devicePixelRatioObservable)===null||e===void 0?void 0:e.value)!==null&&t!==void 0?t:i.devicePixelRatio,a=this._canvasElement.getClientRects(),o=a[0]!==void 0?ou(a[0],n):re({width:this._canvasElementClientSize.width*n,height:this._canvasElementClientSize.height*n});this._suggestNewBitmapSize(o)}}},s.prototype._initResizeObserver=function(){var e=this;this._canvasElement!==null&&(this._canvasElementResizeObserver=new ResizeObserver(function(t){var i=t.find(function(o){return o.target===e._canvasElement});if(!(!i||!i.devicePixelContentBoxSize||!i.devicePixelContentBoxSize[0])){var n=i.devicePixelContentBoxSize[0],a=re({width:n.inlineSize,height:n.blockSize});e._suggestNewBitmapSize(a)}}),this._canvasElementResizeObserver.observe(this._canvasElement,{box:"device-pixel-content-box"}))},s}();function nu(s,e){return new ru(s,e.transform,e.options)}function on(s){return s.ownerDocument.defaultView}function au(){return new Promise(function(s){var e=new ResizeObserver(function(t){s(t.every(function(i){return"devicePixelContentBoxSize"in i})),e.disconnect()});e.observe(document.body,{box:"device-pixel-content-box"})}).catch(function(){return!1})}function ou(s,e){return re({width:Math.round(s.left*e+s.width*e)-Math.round(s.left*e),height:Math.round(s.top*e+s.height*e)-Math.round(s.top*e)})}var lu=function(){function s(e,t,i){if(t.width===0||t.height===0)throw new TypeError("Rendering target could only be created on a media with positive width and height");if(this._mediaSize=t,i.width===0||i.height===0)throw new TypeError("Rendering target could only be created using a bitmap with positive integer width and height");this._bitmapSize=i,this._context=e}return s.prototype.useMediaCoordinateSpace=function(e){try{return this._context.save(),this._context.setTransform(1,0,0,1,0,0),this._context.scale(this._horizontalPixelRatio,this._verticalPixelRatio),e({context:this._context,mediaSize:this._mediaSize})}finally{this._context.restore()}},s.prototype.useBitmapCoordinateSpace=function(e){try{return this._context.save(),this._context.setTransform(1,0,0,1,0,0),e({context:this._context,mediaSize:this._mediaSize,bitmapSize:this._bitmapSize,horizontalPixelRatio:this._horizontalPixelRatio,verticalPixelRatio:this._verticalPixelRatio})}finally{this._context.restore()}},Object.defineProperty(s.prototype,"_horizontalPixelRatio",{get:function(){return this._bitmapSize.width/this._mediaSize.width},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"_verticalPixelRatio",{get:function(){return this._bitmapSize.height/this._mediaSize.height},enumerable:!1,configurable:!0}),s}();function dt(s,e){var t=s.canvasElementClientSize;if(t.width===0||t.height===0)return null;var i=s.bitmapSize;if(i.width===0||i.height===0)return null;var n=s.canvasElement.getContext("2d",e);return n===null?null:new lu(n,t,i)}/*! - * @license - * TradingView Lightweight Charts™ v5.2.1 - * Copyright (c) 2026 TradingView, Inc. - * Licensed under Apache License 2.0 https://www.apache.org/licenses/LICENSE-2.0 - */const Qa={title:"",visible:!0,hitTestTolerance:3,lastValueVisible:!0,priceLineVisible:!0,priceLineSource:0,priceLineWidth:1,priceLineColor:"",priceLineStyle:2,baseLineVisible:!0,baseLineWidth:1,baseLineColor:"#B2B5BE",baseLineStyle:0,priceFormat:{type:"price",precision:2,minMove:.01}};var ln,de;function Xe(s,e){const t=function(i,n){switch(i){case 0:default:return[];case 1:return[n,n];case 2:return[2*n,2*n];case 3:return[6*n,6*n];case 4:return[n,4*n]}}(e,s.lineWidth);return s.setLineDash(t),t}function Ya(s,e,t,i){s.beginPath();const n=s.lineWidth%2?.5:0;s.moveTo(t,e+n),s.lineTo(i,e+n),s.stroke()}function me(s,e){if(!s)throw new Error("Assertion failed"+(e?": "+e:""))}function _e(s){if(s===void 0)throw new Error("Value is undefined");return s}function P(s){if(s===null)throw new Error("Value is null");return s}function Ge(s){return P(_e(s))}(function(s){s[s.Simple=0]="Simple",s[s.WithSteps=1]="WithSteps",s[s.Curved=2]="Curved"})(ln||(ln={})),function(s){s[s.Solid=0]="Solid",s[s.Dotted=1]="Dotted",s[s.Dashed=2]="Dashed",s[s.LargeDashed=3]="LargeDashed",s[s.SparseDotted=4]="SparseDotted"}(de||(de={}));class le{constructor(){this.t=[]}i(e,t,i){const n={h:e,l:t,o:i===!0};this.t.push(n)}_(e){const t=this.t.findIndex(i=>e===i.h);t>-1&&this.t.splice(t,1)}u(e){this.t=this.t.filter(t=>t.l!==e)}p(e,t,i){const n=[...this.t];this.t=this.t.filter(a=>!a.o),n.forEach(a=>a.h(e,t,i))}v(){return this.t.length>0}m(){this.t=[]}}function Me(s,...e){for(const t of e)for(const i in t)t[i]!==void 0&&Object.prototype.hasOwnProperty.call(t,i)&&!["__proto__","constructor","prototype"].includes(i)&&(typeof t[i]!="object"||s[i]===void 0||Array.isArray(t[i])?s[i]=t[i]:Me(s[i],t[i]));return s}function Rt(s){return typeof s=="number"&&isFinite(s)}function rs(s){return typeof s=="number"&&s%1==0}function fs(s){return typeof s=="string"}function Ns(s){return typeof s=="boolean"}function $e(s){const e=s;if(!e||typeof e!="object")return e;let t,i,n;for(i in t=Array.isArray(e)?[]:{},e)e.hasOwnProperty(i)&&(n=e[i],t[i]=n&&typeof n=="object"?$e(n):n);return t}function cn(s){return s!==null}function ns(s){return s===null?void 0:s}const Ja="-apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif";function Ks(s,e,t){return e===void 0&&(e=Ja),`${t=t!==void 0?`${t} `:""}${s}px ${e}`}class cu{constructor(e){this.M={S:1,C:5,P:NaN,k:"",T:"",R:"",D:"",I:0,V:0,B:0,A:0,L:0},this.O=e}N(){const e=this.M,t=this.F(),i=this.W();return e.P===t&&e.T===i||(e.P=t,e.T=i,e.k=Ks(t,i),e.A=2.5/12*t,e.I=e.A,e.V=t/12*e.C,e.B=t/12*e.C,e.L=0),e.R=this.H(),e.D=this.U(),this.M}H(){return this.O.N().layout.textColor}U(){return this.O.$()}F(){return this.O.N().layout.fontSize}W(){return this.O.N().layout.fontFamily}}function Ci(s){return s<0?0:s>255?255:Math.round(s)||0}function dn(s){return .199*s[0]+.687*s[1]+.114*s[2]}class du{constructor(e,t){this.j=new Map,this.q=e,t&&(this.j=t)}Y(e,t){if(e==="transparent")return e;const i=this.K(e),n=i[3];return`rgba(${i[0]}, ${i[1]}, ${i[2]}, ${t*n})`}G(e){const t=this.K(e);return{Z:`rgb(${t[0]}, ${t[1]}, ${t[2]})`,X:dn(t)>160?"black":"white"}}J(e){return dn(this.K(e))}tt(e,t,i){const[n,a,o,l]=this.K(e),[c,d,h,u]=this.K(t),m=[Ci(n+i*(c-n)),Ci(a+i*(d-a)),Ci(o+i*(h-o)),(x=l+i*(u-l),x<=0||x>1?Math.min(Math.max(x,0),1):Math.round(1e4*x)/1e4)];var x;return`rgba(${m[0]}, ${m[1]}, ${m[2]}, ${m[3]})`}K(e){const t=this.j.get(e);if(t)return t;const i=function(o){const l=document.createElement("div");l.style.display="none",document.body.appendChild(l),l.style.color=o;const c=window.getComputedStyle(l).color;return document.body.removeChild(l),c}(e),n=i.match(/^rgba?\s*\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d*\.?\d+))?\)$/);if(!n){if(this.q.length)for(const o of this.q){const l=o(e);if(l)return this.j.set(e,l),l}throw new Error(`Failed to parse color: ${e}`)}const a=[parseInt(n[1],10),parseInt(n[2],10),parseInt(n[3],10),n[4]?parseFloat(n[4]):1];return this.j.set(e,a),a}}class hu{constructor(){this.it=[]}nt(e){this.it=e}st(e,t,i){this.it.forEach(n=>{n.st(e,t,i)})}}class Ue{st(e,t,i){e.useBitmapCoordinateSpace(n=>this.et(n,t,i))}}class uu extends Ue{constructor(){super(...arguments),this.rt=null}ht(e){this.rt=e}et({context:e,horizontalPixelRatio:t,verticalPixelRatio:i}){if(this.rt===null||this.rt.lt===null)return;const n=this.rt.lt,a=this.rt,o=Math.max(1,Math.floor(t))%2/2,l=c=>{e.beginPath();for(let d=n.to-1;d>=n.from;--d){const h=a.ot[d],u=Math.round(h._t*t)+o,m=h.ut*i,x=c*i+o;e.moveTo(u,m),e.arc(u,m,x,0,2*Math.PI)}e.fill()};a.ct>0&&(e.fillStyle=a.dt,l(a.ft+a.ct)),e.fillStyle=a.vt,l(a.ft)}}function mu(){return{ot:[{_t:0,ut:0,wt:0,Mt:0}],vt:"",dt:"",ft:0,ct:0,lt:null}}const pu={from:0,to:1};class fu{constructor(e,t,i){this.gt=new hu,this.bt=[],this.St=[],this.xt=!0,this.O=e,this.Ct=t,this.yt=i,this.gt.nt(this.bt)}Pt(e){this.kt(),this.xt=!0}Tt(){return this.xt&&(this.Rt(),this.xt=!1),this.gt}kt(){const e=this.yt.Dt();e.length!==this.bt.length&&(this.St=e.map(mu),this.bt=this.St.map(t=>{const i=new uu;return i.ht(t),i}),this.gt.nt(this.bt))}Rt(){const e=this.Ct.N().mode===2||!this.Ct.It(),t=this.yt.Vt(),i=this.Ct.Bt(),n=this.O.Et();this.kt(),t.forEach((a,o)=>{const l=this.St[o],c=a.At(i),d=a.Lt();!e&&c!==null&&a.It()&&d!==null?(l.vt=c.zt,l.ft=c.ft,l.ct=c.Ot,l.ot[0].Mt=c.Mt,l.ot[0].ut=a.Ft().Nt(c.Mt,d.Wt),l.dt=c.Ht??this.O.Ut(l.ot[0].ut/a.Ft().$t()),l.ot[0].wt=i,l.ot[0]._t=n.jt(i),l.lt=pu):l.lt=null})}}class xu extends Ue{constructor(e){super(),this.qt=e}et({context:e,bitmapSize:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(this.qt===null)return;const a=this.qt.Yt.It,o=this.qt.Kt.It;if(!a&&!o)return;const l=Math.round(this.qt._t*i),c=Math.round(this.qt.ut*n);e.lineCap="butt",a&&l>=0&&(e.lineWidth=Math.floor(this.qt.Yt.ct*i),e.strokeStyle=this.qt.Yt.R,e.fillStyle=this.qt.Yt.R,Xe(e,this.qt.Yt.Gt),function(d,h,u,m){d.beginPath();const x=d.lineWidth%2?.5:0;d.moveTo(h+x,u),d.lineTo(h+x,m),d.stroke()}(e,l,0,t.height)),o&&c>=0&&(e.lineWidth=Math.floor(this.qt.Kt.ct*n),e.strokeStyle=this.qt.Kt.R,e.fillStyle=this.qt.Kt.R,Xe(e,this.qt.Kt.Gt),Ya(e,c,0,t.width))}}class bu{constructor(e,t){this.xt=!0,this.Zt={Yt:{ct:1,Gt:0,R:"",It:!1},Kt:{ct:1,Gt:0,R:"",It:!1},_t:0,ut:0},this.Xt=new xu(this.Zt),this.Jt=e,this.yt=t}Pt(){this.xt=!0}Tt(e){return this.xt&&(this.Rt(),this.xt=!1),this.Xt}Rt(){const e=this.Jt.It(),t=this.yt.Qt().N().crosshair,i=this.Zt;if(t.mode===2)return i.Kt.It=!1,void(i.Yt.It=!1);i.Kt.It=e&&this.Jt.ti(this.yt),i.Yt.It=e&&this.Jt.ii(),i.Kt.ct=t.horzLine.width,i.Kt.Gt=t.horzLine.style,i.Kt.R=t.horzLine.color,i.Yt.ct=t.vertLine.width,i.Yt.Gt=t.vertLine.style,i.Yt.R=t.vertLine.color,i._t=this.Jt.ni(),i.ut=this.Jt.si()}}function gu(s,e,t,i,n,a){s.fillRect(e+a,t,i-2*a,a),s.fillRect(e+a,t+n-a,i-2*a,a),s.fillRect(e,t,a,n),s.fillRect(e+i-a,t,a,n)}function di(s,e,t,i,n,a){s.save(),s.globalCompositeOperation="copy",s.fillStyle=a,s.fillRect(e,t,i,n),s.restore()}function hn(s,e,t,i,n,a){s.beginPath(),s.roundRect?s.roundRect(e,t,i,n,a):(s.lineTo(e+i-a[1],t),a[1]!==0&&s.arcTo(e+i,t,e+i,t+a[1],a[1]),s.lineTo(e+i,t+n-a[2]),a[2]!==0&&s.arcTo(e+i,t+n,e+i-a[2],t+n,a[2]),s.lineTo(e+a[3],t+n),a[3]!==0&&s.arcTo(e,t+n,e,t+n-a[3],a[3]),s.lineTo(e,t+a[0]),a[0]!==0&&s.arcTo(e,t,e+a[0],t,a[0]))}function un(s,e,t,i,n,a,o=0,l=[0,0,0,0],c=""){if(s.save(),!o||!c||c===a)return hn(s,e,t,i,n,l),s.fillStyle=a,s.fill(),void s.restore();const d=o/2;var h;hn(s,e+d,t+d,i-o,n-o,(h=-d,l.map(u=>u===0?u:u+h))),a!=="transparent"&&(s.fillStyle=a,s.fill()),c!=="transparent"&&(s.lineWidth=o,s.strokeStyle=c,s.closePath(),s.stroke()),s.restore()}function Xa(s,e,t,i,n,a,o){s.save(),s.globalCompositeOperation="copy";const l=s.createLinearGradient(0,0,0,n);l.addColorStop(0,a),l.addColorStop(1,o),s.fillStyle=l,s.fillRect(e,t,i,n),s.restore()}class mn{constructor(e,t){this.ht(e,t)}ht(e,t){this.qt=e,this.ei=t}$t(e,t){return this.qt.It?e.P+e.A+e.I:0}st(e,t,i,n){if(!this.qt.It||this.qt.ri.length===0)return;const a=this.qt.R,o=this.ei.Z,l=e.useBitmapCoordinateSpace(c=>{const d=c.context;d.font=t.k;const h=this.hi(c,t,i,n),u=h.ai;return h.li?un(d,u.oi,u._i,u.ui,u.ci,o,u.di,[u.ft,0,0,u.ft],o):un(d,u.fi,u._i,u.ui,u.ci,o,u.di,[0,u.ft,u.ft,0],o),this.qt.pi&&(d.fillStyle=a,d.fillRect(u.fi,u.mi,u.wi-u.fi,u.Mi)),this.qt.gi&&(d.fillStyle=t.D,d.fillRect(h.li?u.bi-u.di:0,u._i,u.di,u.Si-u._i)),h});e.useMediaCoordinateSpace(({context:c})=>{const d=l.xi;c.font=t.k,c.textAlign=l.li?"right":"left",c.textBaseline="middle",c.fillStyle=a,c.fillText(this.qt.ri,d.Ci,(d._i+d.Si)/2+d.yi)})}hi(e,t,i,n){const{context:a,bitmapSize:o,mediaSize:l,horizontalPixelRatio:c,verticalPixelRatio:d}=e,h=this.qt.pi||!this.qt.Pi?t.C:0,u=this.qt.ki?t.S:0,m=t.A+this.ei.Ti,x=t.I+this.ei.Ri,b=t.V,f=t.B,v=this.qt.ri,p=t.P,g=i.Di(a,v),S=Math.ceil(i.Ii(a,v)),j=p+m+x,k=t.S+b+f+S+h,C=Math.max(1,Math.floor(d));let M=Math.round(j*d);M%2!=C%2&&(M+=1);const L=u>0?Math.max(1,Math.floor(u*c)):0,I=Math.round(k*c),R=Math.round(h*c),T=this.ei.Vi??this.ei.Bi??this.ei.Ei,E=Math.round(T*d)-Math.floor(.5*d),F=Math.floor(E+C/2-M/2),B=F+M,z=n==="right",V=z?l.width-u:u,q=z?o.width-L:L;let J,oe,$;return z?(J=q-I,oe=q-R,$=V-h-b-u):(J=q+I,oe=q+R,$=V+h+b),{li:z,ai:{_i:F,mi:E,Si:B,ui:I,ci:M,ft:2*c,di:L,oi:J,fi:q,wi:oe,Mi:C,bi:o.width},xi:{_i:F/d,Si:B/d,Ci:$,yi:g}}}}class hi{constructor(e){this.Ai={Ei:0,Z:"#000",Ri:0,Ti:0},this.Li={ri:"",It:!1,pi:!0,Pi:!1,Ht:"",R:"#FFF",gi:!1,ki:!1},this.zi={ri:"",It:!1,pi:!1,Pi:!0,Ht:"",R:"#FFF",gi:!0,ki:!0},this.xt=!0,this.Oi=new(e||mn)(this.Li,this.Ai),this.Ni=new(e||mn)(this.zi,this.Ai)}ri(){return this.Fi(),this.Li.ri}Ei(){return this.Fi(),this.Ai.Ei}Pt(){this.xt=!0}$t(e,t=!1){return Math.max(this.Oi.$t(e,t),this.Ni.$t(e,t))}Wi(){return this.Ai.Vi??null}Hi(){return this.Ai.Vi??this.Ai.Bi??this.Ei()}Ui(e){this.Ai.Bi=e??void 0}$i(){return this.Fi(),this.Li.It||this.zi.It}ji(){return this.Fi(),this.Li.It}Tt(e){return this.Fi(),this.Li.pi=this.Li.pi&&e.N().ticksVisible,this.zi.pi=this.zi.pi&&e.N().ticksVisible,this.Oi.ht(this.Li,this.Ai),this.Ni.ht(this.zi,this.Ai),this.Oi}qi(){return this.Fi(),this.Oi.ht(this.Li,this.Ai),this.Ni.ht(this.zi,this.Ai),this.Ni}Fi(){this.xt&&(this.Li.pi=!0,this.zi.pi=!1,this.Yi(this.Li,this.zi,this.Ai))}}class vu extends hi{constructor(e,t,i){super(),this.Jt=e,this.Ki=t,this.Gi=i}Yi(e,t,i){if(e.It=!1,this.Jt.N().mode===2)return;const n=this.Jt.N().horzLine;if(!n.labelVisible)return;const a=this.Ki.Lt();if(!this.Jt.It()||this.Ki.Zi()||a===null)return;const o=this.Ki.Xi().G(n.labelBackgroundColor);i.Z=o.Z,e.R=o.X;const l=2/12*this.Ki.P();i.Ti=l,i.Ri=l;const c=this.Gi(this.Ki);i.Ei=c.Ei,e.ri=this.Ki.Ji(c.Mt,a),e.It=!0}}const yu=/[1-9]/g;class Za{constructor(){this.qt=null}ht(e){this.qt=e}st(e,t){if(this.qt===null||this.qt.It===!1||this.qt.ri.length===0)return;const i=e.useMediaCoordinateSpace(({context:m})=>(m.font=t.k,Math.round(t.Qi.Ii(m,P(this.qt).ri,yu))));if(i<=0)return;const n=t.tn,a=i+2*n,o=a/2,l=this.qt.nn;let c=this.qt.Ei,d=Math.floor(c-o)+.5;d<0?(c+=Math.abs(0-d),d=Math.floor(c-o)+.5):d+a>l&&(c-=Math.abs(l-(d+a)),d=Math.floor(c-o)+.5);const h=d+a,u=Math.ceil(0+t.S+t.C+t.A+t.P+t.I);e.useBitmapCoordinateSpace(({context:m,horizontalPixelRatio:x,verticalPixelRatio:b})=>{const f=P(this.qt);m.fillStyle=f.Z;const v=Math.round(d*x),p=Math.round(0*b),g=Math.round(h*x),S=Math.round(u*b),j=Math.round(2*x);if(m.beginPath(),m.moveTo(v,p),m.lineTo(v,S-j),m.arcTo(v,S,v+j,S,j),m.lineTo(g-j,S),m.arcTo(g,S,g,S-j,j),m.lineTo(g,p),m.fill(),f.pi){const k=Math.round(f.Ei*x),C=p,M=Math.round((C+t.C)*b);m.fillStyle=f.R;const L=Math.max(1,Math.floor(x)),I=Math.floor(.5*x);m.fillRect(k-I,C,L,M-C)}}),e.useMediaCoordinateSpace(({context:m})=>{const x=P(this.qt),b=0+t.S+t.C+t.A+t.P/2;m.font=t.k,m.textAlign="left",m.textBaseline="middle",m.fillStyle=x.R;const f=t.Qi.Di(m,"Apr0");m.translate(d+n,b+f),m.fillText(x.ri,0,0)})}}class wu{constructor(e,t,i){this.xt=!0,this.Xt=new Za,this.Zt={It:!1,Z:"#4c525e",R:"white",ri:"",nn:0,Ei:NaN,pi:!0},this.Ct=e,this.sn=t,this.Gi=i}Pt(){this.xt=!0}Tt(){return this.xt&&(this.Rt(),this.xt=!1),this.Xt.ht(this.Zt),this.Xt}Rt(){const e=this.Zt;if(e.It=!1,this.Ct.N().mode===2)return;const t=this.Ct.N().vertLine;if(!t.labelVisible)return;const i=this.sn.Et();if(i.Zi())return;e.nn=i.nn();const n=this.Gi();if(n===null)return;e.Ei=n.Ei;const a=i.en(this.Ct.Bt());e.ri=i.rn(P(a)),e.It=!0;const o=this.sn.Xi().G(t.labelBackgroundColor);e.Z=o.Z,e.R=o.X,e.pi=i.N().ticksVisible}}class eo{constructor(){this.hn=null,this.an=0}ln(){return this.an}_n(e){this.an=e}Ft(){return this.hn}un(e){this.hn=e}cn(e){return[]}dn(){return[]}It(){return!0}}var Pt;(function(s){s[s.Normal=0]="Normal",s[s.Magnet=1]="Magnet",s[s.Hidden=2]="Hidden",s[s.MagnetOHLC=3]="MagnetOHLC"})(Pt||(Pt={}));class Nu extends eo{constructor(e,t){super(),this.yt=null,this.fn=NaN,this.pn=0,this.vn=!1,this.mn=new Map,this.wn=!1,this.Mn=new WeakMap,this.gn=new WeakMap,this.bn=NaN,this.Sn=NaN,this.xn=NaN,this.Cn=NaN,this.sn=e,this.yn=t,this.Pn=((n,a)=>o=>{const l=a(),c=n();if(o===P(this.yt).kn())return{Mt:c,Ei:l};{const d=P(o.Lt());return{Mt:o.Tn(l,d),Ei:l}}})(()=>this.fn,()=>this.Sn);const i=((n,a)=>()=>{const o=this.sn.Et().Rn(n()),l=a();return o&&Number.isFinite(l)?{wt:o,Ei:l}:null})(()=>this.pn,()=>this.ni());this.Dn=new wu(this,e,i)}N(){return this.yn}In(e,t){this.xn=e,this.Cn=t}Vn(){this.xn=NaN,this.Cn=NaN}Bn(){return this.xn}En(){return this.Cn}An(e,t,i){this.wn||(this.wn=!0),this.vn=!0,this.Ln(e,t,i)}Bt(){return this.pn}ni(){return this.bn}si(){return this.Sn}It(){return this.vn}zn(){this.vn=!1,this.On(),this.fn=NaN,this.bn=NaN,this.Sn=NaN,this.yt=null,this.Vn(),this.Nn()}Fn(e){if(!this.yn.doNotSnapToHiddenSeriesIndices)return e;const t=this.sn,i=t.Et();let n=null,a=null;for(const d of t.Wn()){const h=d.Un().Hn(e,-1);if(h){if(h.$n===e)return e;(n===null||h.$n>n)&&(n=h.$n)}const u=d.Un().Hn(e,1);if(u){if(u.$n===e)return e;(a===null||u.$nMath.abs(l-i.jt(d)));return o[c.indexOf(Math.min(...c))]}jn(e){let t=this.Mn.get(e);t||(t=new bu(this,e),this.Mn.set(e,t));let i=this.gn.get(e);return i||(i=new fu(this.sn,this,e),this.gn.set(e,i)),[t,i]}ti(e){return e===this.yt&&this.yn.horzLine.visible}ii(){return this.yn.vertLine.visible}qn(e,t){this.vn&&this.yt===e||this.mn.clear();const i=[];return this.yt===e&&i.push(this.Yn(this.mn,t,this.Pn)),i}dn(){return this.vn?[this.Dn]:[]}Kn(){return this.yt}Nn(){this.sn.Gn().forEach(e=>{this.Mn.get(e)?.Pt(),this.gn.get(e)?.Pt()}),this.mn.forEach(e=>e.Pt()),this.Dn.Pt()}Zn(e){return e&&!e.kn().Zi()?e.kn():null}Ln(e,t,i){this.Xn(e,t,i)&&this.Nn()}Xn(e,t,i){const n=this.bn,a=this.Sn,o=this.fn,l=this.pn,c=this.yt,d=this.Zn(i);this.pn=e,this.bn=isNaN(e)?NaN:this.sn.Et().jt(e),this.yt=i;const h=d!==null?d.Lt():null;return d!==null&&h!==null?(this.fn=t,this.Sn=d.Nt(t,h)):(this.fn=NaN,this.Sn=NaN),n!==this.bn||a!==this.Sn||l!==this.pn||o!==this.fn||c!==this.yt}On(){const e=this.sn.Jn().map(i=>i.Un().Qn()).filter(cn),t=e.length===0?null:Math.max(...e);this.pn=t!==null?t:NaN}Yn(e,t,i){let n=e.get(t);return n===void 0&&(n=new vu(this,t,i),e.set(t,n)),n}}function ui(s){return s==="left"||s==="right"}class ue{constructor(e){this.ts=new Map,this.ns=[],this.ss=e}es(e,t){const i=function(n,a){return n===void 0?a:{rs:Math.max(n.rs,a.rs),hs:n.hs||a.hs}}(this.ts.get(e),t);this.ts.set(e,i)}ls(){return this.ss}_s(e){const t=this.ts.get(e);return t===void 0?{rs:this.ss}:{rs:Math.max(this.ss,t.rs),hs:t.hs}}us(){this.cs(),this.ns=[{ds:0}]}fs(e){this.cs(),this.ns=[{ds:1,Wt:e}]}ps(e){this.vs(),this.ns.push({ds:5,Wt:e})}cs(){this.vs(),this.ns.push({ds:6})}ws(){this.cs(),this.ns=[{ds:4}]}Ms(e){this.cs(),this.ns.push({ds:2,Wt:e})}gs(e){this.cs(),this.ns.push({ds:3,Wt:e})}bs(){return this.ns}Ss(e){for(const t of e.ns)this.xs(t);this.ss=Math.max(this.ss,e.ss),e.ts.forEach((t,i)=>{this.es(i,t)})}static Cs(){return new ue(2)}static ys(){return new ue(3)}xs(e){switch(e.ds){case 0:this.us();break;case 1:this.fs(e.Wt);break;case 2:this.Ms(e.Wt);break;case 3:this.gs(e.Wt);break;case 4:this.ws();break;case 5:this.ps(e.Wt);break;case 6:this.vs()}}vs(){const e=this.ns.findIndex(t=>t.ds===5);e!==-1&&this.ns.splice(e,1)}}class to{formatTickmarks(e){return e.map(t=>this.format(t))}}const pn=".";function De(s,e){if(!Rt(s))return"n/a";if(!rs(e))throw new TypeError("invalid length");if(e<0||e>16)throw new TypeError("invalid length");return e===0?s.toString():("0000000000000000"+s.toString()).slice(-e)}class mi extends to{constructor(e,t){if(super(),t||(t=1),Rt(e)&&rs(e)||(e=100),e<0)throw new TypeError("invalid base");this.Ki=e,this.Ps=t,this.ks()}format(e){const t=e<0?"−":"";return e=Math.abs(e),t+this.Ts(e)}ks(){if(this.Rs=0,this.Ki>0&&this.Ps>0){let e=this.Ki;for(;e>1;)e/=10,this.Rs++}}Ts(e){const t=this.Ki/this.Ps;let i=Math.floor(e),n="";const a=this.Rs!==void 0?this.Rs:NaN;if(t>1){let o=+(Math.round(e*t)-i*t).toFixed(this.Rs);o>=t&&(o-=t,i+=1),n=pn+De(+o.toFixed(this.Rs)*this.Ps,a)}else i=Math.round(i*t)/t,a>0&&(n=pn+De(0,a));return i.toFixed(0)+n}}class so extends mi{constructor(e=100){super(e)}format(e){return`${super.format(e)}%`}}class ju extends to{constructor(e){super(),this.Ds=e}format(e){let t="";return e<0&&(t="-",e=-e),e<995?t+this.Is(e):e<999995?t+this.Is(e/1e3)+"K":e<999999995?(e=1e3*Math.round(e/1e3),t+this.Is(e/1e6)+"M"):(e=1e6*Math.round(e/1e6),t+this.Is(e/1e9)+"B")}Is(e){let t;const i=Math.pow(10,this.Ds);return t=(e=Math.round(e*i)/i)>=1e-15&&e<1?e.toFixed(this.Ds).replace(/\.?0+$/,""):String(e),t.replace(/(\.[1-9]*)0+$/,(n,a)=>a)}}const _u=/[2-9]/g;class Gs{constructor(e=50){this.Vs=0,this.Bs=1,this.Es=1,this.As={},this.Ls=new Map,this.zs=e}Os(){this.Vs=0,this.Ls.clear(),this.Bs=1,this.Es=1,this.As={}}Ii(e,t,i){return this.Ns(e,t,i).width}Di(e,t,i){const n=this.Ns(e,t,i);return((n.actualBoundingBoxAscent||0)-(n.actualBoundingBoxDescent||0))/2}Ns(e,t,i){const n=i||_u,a=String(t).replace(n,"0");if(this.Ls.has(a))return _e(this.Ls.get(a)).Fs;if(this.Vs===this.zs){const l=this.As[this.Es];delete this.As[this.Es],this.Ls.delete(l),this.Es++,this.Vs--}e.save(),e.textBaseline="middle";const o=e.measureText(a);return e.restore(),o.width===0&&t.length||(this.Ls.set(a,{Fs:o,Ws:this.Bs}),this.As[this.Bs]=a,this.Vs++,this.Bs++),o}}class Su{constructor(e){this.Hs=null,this.M=null,this.Us="right",this.$s=e}js(e,t,i){this.Hs=e,this.M=t,this.Us=i}st(e){this.M!==null&&this.Hs!==null&&this.Hs.st(e,this.M,this.$s,this.Us)}}class io{constructor(e,t,i){this.qs=e,this.$s=new Gs(50),this.Ys=t,this.O=i,this.F=-1,this.Xt=new Su(this.$s)}Tt(){const e=this.O.Ks(this.Ys);if(e===null)return null;const t=e.Gs(this.Ys)?e.Zs():this.Ys.Ft();if(t===null)return null;const i=e.Xs(t);if(i==="overlay")return null;const n=this.O.Js();return n.P!==this.F&&(this.F=n.P,this.$s.Os()),this.Xt.js(this.qs.qi(),n,i),this.Xt}}class ku extends Ue{constructor(){super(...arguments),this.qt=null}ht(e){this.qt=e}Qs(e,t){if(!this.qt?.It)return null;const{ut:i,ct:n,te:a}=this.qt;return t>=i-n-7&&t<=i+n+7?{ie:this.qt,ne:Math.abs(t-i),se:2,ee:"price-line",te:a}:null}et({context:e,bitmapSize:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(this.qt===null||this.qt.It===!1)return;const a=Math.round(this.qt.ut*n);a<0||a>t.height||(e.lineCap="butt",e.strokeStyle=this.qt.R,e.lineWidth=Math.floor(this.qt.ct*i),Xe(e,this.qt.Gt),Ya(e,a,0,t.width))}}class yr{constructor(e){this.re={ut:0,R:"rgba(0, 0, 0, 0)",ct:1,Gt:0,It:!1},this.he=new ku,this.xt=!0,this.ae=e,this.le=e.Qt(),this.he.ht(this.re)}Pt(){this.xt=!0}Tt(){return this.ae.It()?(this.xt&&(this.oe(),this.xt=!1),this.he):null}}class Mu extends yr{constructor(e){super(e)}oe(){this.re.It=!1;const e=this.ae.Ft(),t=e._e()._e;if(t!==2&&t!==3)return;const i=this.ae.N();if(!i.baseLineVisible||!this.ae.It())return;const n=this.ae.Lt();n!==null&&(this.re.It=!0,this.re.ut=e.Nt(n.Wt,n.Wt),this.re.R=i.baseLineColor,this.re.ct=i.baseLineWidth,this.re.Gt=i.baseLineStyle)}}class Cu extends Ue{constructor(){super(...arguments),this.qt=null}ht(e){this.qt=e}ue(){return this.qt}et({context:e,horizontalPixelRatio:t,verticalPixelRatio:i}){const n=this.qt;if(n===null)return;const a=Math.max(1,Math.floor(t)),o=a%2/2,l=Math.round(n.ce.x*t)+o,c=n.ce.y*i;e.fillStyle=n.de,e.beginPath();const d=Math.max(2,1.5*n.fe)*t;e.arc(l,c,d,0,2*Math.PI,!1),e.fill(),e.fillStyle=n.pe,e.beginPath(),e.arc(l,c,n.ft*t,0,2*Math.PI,!1),e.fill(),e.lineWidth=a,e.strokeStyle=n.ve,e.beginPath(),e.arc(l,c,n.ft*t+a/2,0,2*Math.PI,!1),e.stroke()}}const Eu=[{me:0,we:.25,Me:4,ge:10,be:.25,Se:0,xe:.4,Ce:.8},{me:.25,we:.525,Me:10,ge:14,be:0,Se:0,xe:.8,Ce:0},{me:.525,we:1,Me:14,ge:14,be:0,Se:0,xe:0,Ce:0}];class Tu{constructor(e){this.Xt=new Cu,this.xt=!0,this.ye=!0,this.Pe=performance.now(),this.ke=this.Pe-1,this.Te=e}Re(){this.ke=this.Pe-1,this.Pt()}De(){if(this.Pt(),this.Te.N().lastPriceAnimation===2){const e=performance.now(),t=this.ke-e;if(t>0)return void(t<650&&(this.ke+=2600));this.Pe=e,this.ke=e+2600}}Pt(){this.xt=!0}Ie(){this.ye=!0}It(){return this.Te.N().lastPriceAnimation!==0}Ve(){switch(this.Te.N().lastPriceAnimation){case 0:return!1;case 1:return!0;case 2:return performance.now()<=this.ke}}Tt(){return this.xt?(this.Rt(),this.xt=!1,this.ye=!1):this.ye&&(this.Be(),this.ye=!1),this.Xt}Rt(){this.Xt.ht(null);const e=this.Te.Qt().Et(),t=e.Ee(),i=this.Te.Lt();if(t===null||i===null)return;const n=this.Te.Ae(!0);if(n.Le||!t.ze(n.$n))return;const a={x:e.jt(n.$n),y:this.Te.Ft().Nt(n.Mt,i.Wt)},o=n.R,l=this.Te.N().lineWidth,c=this.Oe(this.Ne(),o);this.Xt.ht({de:o,fe:l,pe:c.pe,ve:c.ve,ft:c.ft,ce:a})}Be(){const e=this.Xt.ue();if(e!==null){const t=this.Oe(this.Ne(),e.de);e.pe=t.pe,e.ve=t.ve,e.ft=t.ft}}Ne(){return this.Ve()?performance.now()-this.Pe:2599}Fe(e,t,i,n){const a=i+(n-i)*t;return this.Te.Qt().Xi().Y(e,a)}Oe(e,t){const i=e%2600/2600;let n;for(const d of Eu)if(i>=d.me&&i<=d.we){n=d;break}me(n!==void 0,"Last price animation internal logic error");const a=(i-n.me)/(n.we-n.me);return{pe:this.Fe(t,a,n.be,n.Se),ve:this.Fe(t,a,n.xe,n.Ce),ft:(o=a,l=n.Me,c=n.ge,l+(c-l)*o)};var o,l,c}}class Ru extends yr{constructor(e){super(e)}oe(){const e=this.re;e.It=!1;const t=this.ae.N();if(!t.priceLineVisible||!this.ae.It())return;const i=this.ae.Ae(t.priceLineSource===0);i.Le||(e.It=!0,e.ut=i.Ei,e.R=this.ae.We(i.R),e.ct=t.priceLineWidth,e.Gt=t.priceLineStyle)}}class Pu extends hi{constructor(e){super(),this.Jt=e}Yi(e,t,i){e.It=!1,t.It=!1;const n=this.Jt;if(!n.It())return;const a=n.N(),o=a.lastValueVisible,l=n.He()!=="",c=a.seriesLastValueMode===0,d=n.Ae(!1);if(d.Le)return;o&&(e.ri=this.Ue(d,o,c),e.It=e.ri.length!==0),(l||c)&&(t.ri=this.$e(d,o,l,c),t.It=t.ri.length>0);const h=n.We(d.R),u=this.Jt.Qt().Xi().G(h);i.Z=u.Z,i.Ei=d.Ei,t.Ht=n.Qt().Ut(d.Ei/n.Ft().$t()),e.Ht=h,e.R=u.X,t.R=u.X}$e(e,t,i,n){let a="";const o=this.Jt.He();return i&&o.length!==0&&(a+=`${o} `),t&&n&&(a+=this.Jt.Ft().je()?e.qe:e.Ye),a.trim()}Ue(e,t,i){return t?i?this.Jt.Ft().je()?e.Ye:e.qe:e.ri:""}}function fn(s,e,t,i){const n=Number.isFinite(e),a=Number.isFinite(t);return n&&a?s(e,t):n||a?n?e:t:i}class ye{constructor(e,t){this.Ke=e,this.Ge=t}Ze(e){return e!==null&&this.Ke===e.Ke&&this.Ge===e.Ge}Xe(){return new ye(this.Ke,this.Ge)}Je(){return this.Ke}Qe(){return this.Ge}tr(){return this.Ge-this.Ke}Zi(){return this.Ge===this.Ke||Number.isNaN(this.Ge)||Number.isNaN(this.Ke)}Ss(e){return e===null?this:new ye(fn(Math.min,this.Je(),e.Je(),-1/0),fn(Math.max,this.Qe(),e.Qe(),1/0))}ir(e){if(!Rt(e)||this.Ge-this.Ke===0)return;const t=.5*(this.Ge+this.Ke);let i=this.Ge-t,n=this.Ke-t;i*=e,n*=e,this.Ge=t+i,this.Ke=t+n}nr(e){Rt(e)&&(this.Ge+=e,this.Ke+=e)}sr(){return{minValue:this.Ke,maxValue:this.Ge}}static er(e){return e===null?null:new ye(e.minValue,e.maxValue)}}class Qs{constructor(e,t){this.rr=e,this.hr=t||null}ar(){return this.rr}lr(){return this.hr}sr(){return{priceRange:this.rr===null?null:this.rr.sr(),margins:this.hr||void 0}}static er(e){return e===null?null:new Qs(ye.er(e.priceRange),e.margins)}}const Lu=[2,4,8,16,32,64,128,256,512],Au="Custom series with conflation reducer must have a priceValueBuilder method";class Ou extends yr{constructor(e,t){super(e),this._r=t}oe(){const e=this.re;e.It=!1;const t=this._r.N();if(!this.ae.It()||!t.lineVisible)return;const i=this._r.ur();i!==null&&(e.It=!0,e.ut=i,e.R=t.color,e.ct=t.lineWidth,e.Gt=t.lineStyle,e.te=this._r.N().id)}}class zu extends hi{constructor(e,t){super(),this.Te=e,this._r=t}Yi(e,t,i){e.It=!1,t.It=!1;const n=this._r.N(),a=n.axisLabelVisible,o=n.title!=="",l=this.Te;if(!a||!l.It())return;const c=this._r.ur();if(c===null)return;o&&(t.ri=n.title,t.It=!0),t.Ht=l.Qt().Ut(c/l.Ft().$t()),e.ri=this.cr(n.price),e.It=!0;const d=this.Te.Qt().Xi().G(n.axisLabelColor||n.color);i.Z=d.Z;const h=n.axisLabelTextColor||d.X;e.R=h,t.R=h,i.Ei=c}cr(e){const t=this.Te.Lt();return t===null?"":this.Te.Ft().Ji(e,t.Wt)}}class Iu{constructor(e,t){this.Te=e,this.yn=t,this.dr=new Ou(e,this),this.qs=new zu(e,this),this.pr=new io(this.qs,e,e.Qt())}vr(e){Me(this.yn,e),this.Pt(),this.Te.Qt().mr()}N(){return this.yn}wr(){return this.dr}Mr(){return this.pr}gr(){return this.qs}Pt(){this.dr.Pt(),this.qs.Pt()}ur(){const e=this.Te,t=e.Ft();if(e.Qt().Et().Zi()||t.Zi())return null;const i=e.Lt();return i===null?null:t.Nt(this.yn.price,i.Wt)}}class $u{constructor(){this.br=new WeakMap}Sr(e,t,i){const n=1/t*i;if(e>=n)return 1;const a=n/e,o=Math.pow(2,Math.floor(Math.log2(a)));return Math.min(o,512)}Cr(e,t,i,n=!1,a){if(e.length===0||t<=1)return e;const o=this.yr(t);if(o<=1)return e;const l=this.Pr(e);let c=l.kr.get(o);return c!==void 0||(c=this.Tr(e,o,i,n,a,l.kr),l.kr.set(o,c)),c}Rr(e,t,i,n,a=!1,o){if(i<1||e.length===0)return e;const l=this.Pr(e),c=l.kr.get(i);if(!c)return this.Cr(e,i,n,a,o);const d=this.Dr(e,t,i,c,a,n,o);return l.kr.set(i,d),d}yr(e){if(e<=2)return 2;for(const t of Lu)if(e<=t)return t;return 512}Ir(e){if(e.length===0)return 0;const t=e[0],i=e[e.length-1];return 31*e.length+17*t.$n+13*i.$n}Tr(e,t,i,n=!1,a,o=new Map){if(t===2)return this.Vr(e,2,i,n,a);const l=t/2;let c=o.get(l);return c||(c=this.Tr(e,l,i,n,a,o),o.set(l,c)),this.Br(c,i,n,a)}Vr(e,t,i,n=!1,a){const o=this.Er(e,t,i,n,a);return this.Ar(o,n)}Br(e,t,i=!1,n){const a=this.Er(e,2,t,i,n);return this.Ar(a,i)}Er(e,t,i,n=!1,a){const o=[];for(let l=0;l=t){const c=this.Lr(e[l],e[l+1],i,n,a);c.zr=!1,o.push(c)}else if(o.length===0)o.push(this.Or(e[l],!0));else{const c=o[o.length-1];o[o.length-1]=this.Nr(c,e[l],i,n,a)}return o}Fr(e,t){return(e??1)+(t??1)}Lr(e,t,i,n=!1,a){if(!n||!i||!a){const d=e.Wt[1]>t.Wt[1]?e.Wt[1]:t.Wt[1],h=e.Wt[2]t.Wt[1]?e.qr:t.Wt[1],Yr:e.Yrthis.th(i,t))}Dr(e,t,i,n,a=!1,o,l){if(n.length===0)return n;const c=e.length-1,d=Math.floor(c/i)*i;if(Math.min(d+i,e.length)-di){const h=e.slice();return h[h.length-1]=t,this.Cr(h,i,o,a,l)}if(Math.floor((c-1)/i)===Math.floor(c/i)||n.length===1){const h=Math.min(d+i,e.length),u=h-d;if(u<=0)return n;const m=u===1?this.Or(d===c?t:e[d],!0):this.Jr(e,d,h,c,t,o,a,l);return n[n.length-1]=this.th(m,a),n}{const h=e.slice();return h[h.length-1]=t,this.Cr(h,i,o,a,l)}}Or(e,t=!1){return{Wr:e.$n,Hr:e.$n,Ur:e.wt,$r:e.wt,jr:e.Wt[0],qr:e.Wt[1],Yr:e.Wt[2],Kr:e.Wt[3],Gr:e.Gr??1,Zr:e.ue,zr:t}}Pr(e){const t=this.ih(e),i=this.Ir(e);return t.nh!==i&&(t.kr.clear(),t.nh=i),t}ih(e){let t=this.br.get(e);return t===void 0&&(t={nh:this.Ir(e),kr:new Map},this.br.set(e,t)),t}}class Du extends eo{constructor(e){super(),this.sn=e}Qt(){return this.sn}}const Bu={Bar:(s,e,t,i)=>{const n=e.upColor,a=e.downColor,o=P(s(t,i)),l=Ge(o.Wt[0])<=Ge(o.Wt[3]);return{sh:o.R??(l?n:a)}},Candlestick:(s,e,t,i)=>{const n=e.upColor,a=e.downColor,o=e.borderUpColor,l=e.borderDownColor,c=e.wickUpColor,d=e.wickDownColor,h=P(s(t,i)),u=Ge(h.Wt[0])<=Ge(h.Wt[3]);return{sh:h.R??(u?n:a),eh:h.Ht??(u?o:l),rh:h.hh??(u?c:d)}},Custom:(s,e,t,i)=>({sh:P(s(t,i)).R??e.color}),Area:(s,e,t,i)=>{const n=P(s(t,i));return{sh:n.vt??e.lineColor,vt:n.vt??e.lineColor,ah:n.ah??e.topColor,oh:n.oh??e.bottomColor}},Baseline:(s,e,t,i)=>{const n=P(s(t,i));return{sh:n.Wt[3]>=e.baseValue.price?e.topLineColor:e.bottomLineColor,_h:n._h??e.topLineColor,uh:n.uh??e.bottomLineColor,dh:n.dh??e.topFillColor1,fh:n.fh??e.topFillColor2,ph:n.ph??e.bottomFillColor1,mh:n.mh??e.bottomFillColor2}},Line:(s,e,t,i)=>{const n=P(s(t,i));return{sh:n.R??e.color,vt:n.R??e.color}},Histogram:(s,e,t,i)=>({sh:P(s(t,i)).R??e.color})};class Fu{constructor(e){this.wh=(t,i)=>i!==void 0?i.Wt:this.Te.Un().Mh(t),this.Te=e,this.gh=Bu[e.bh()]}Sh(e,t){return this.gh(this.wh,this.Te.N(),e,t)}}function ro(s,e,t,i,n=0,a=e.length){let o=a-n;for(;0>1,c=n+l;i(e[c],t)===s?(n=c+1,o-=l+1):o=l}return n}const ht=ro.bind(null,!0),wr=ro.bind(null,!1);var xn;(function(s){s[s.NearestLeft=-1]="NearestLeft",s[s.None=0]="None",s[s.NearestRight=1]="NearestRight"})(xn||(xn={}));const Ke=30;class Uu{constructor(){this.xh=[],this.Ch=new Map,this.yh=new Map,this.Ph=[]}kh(){return this.Th()>0?this.xh[this.xh.length-1]:null}Rh(){return this.Th()>0?this.Dh(0):null}Qn(){return this.Th()>0?this.Dh(this.xh.length-1):null}Th(){return this.xh.length}Zi(){return this.Th()===0}ze(e){return this.Ih(e,0)!==null}Mh(e){return this.Hn(e)}Hn(e,t=0){const i=this.Ih(e,t);return i===null?null:{...this.Vh(i),$n:this.Dh(i)}}Bh(){return this.xh}Eh(e,t,i){if(this.Zi())return null;let n=null;for(const a of i)n=js(n,this.Ah(e,t,a));return n}ht(e){this.yh.clear(),this.Ch.clear(),this.xh=e,this.Ph=e.map(t=>t.$n)}Lh(){return this.Ph}Dh(e){return this.xh[e].$n}Vh(e){return this.xh[e]}Ih(e,t){const i=this.zh(e);if(i===null&&t!==0)switch(t){case-1:return this.Oh(e);case 1:return this.Nh(e);default:throw new TypeError("Unknown search mode")}return i}Oh(e){let t=this.Fh(e);return t>0&&(t-=1),t!==this.xh.length&&this.Dh(t)t.$nt.$n>i)}Hh(e,t,i){let n=null;for(let a=e;an.$h&&(n.$h=o)))}return n}Ah(e,t,i){if(this.Zi())return null;let n=null;const a=P(this.Rh()),o=P(this.Qn()),l=Math.max(e,a),c=Math.min(t,o),d=Math.ceil(l/Ke)*Ke,h=Math.max(d,Math.floor(c/Ke)*Ke);{const m=this.Fh(l),x=this.Wh(Math.min(c,d,t));n=js(n,this.Hh(m,x,i))}let u=this.Ch.get(i);u===void 0&&(u=new Map,this.Ch.set(i,u));for(let m=Math.max(d+1,l);mnew Wu(i));return this.Xh={Kh:e,Gh:t},t}Qs(e,t){return this.Jh.hitTest?.(e,t)??null}}let Hu=class extends no{cn(){return[]}};class Vu{constructor(e){this.jh=e}st(e,t,i){this.jh.draw(e,Ys)}qh(e,t,i){this.jh.drawBackground?.(e,Ys)}}class bn{constructor(e){this.Ls=null,this.Yh=e}Tt(){const e=this.Yh.renderer();if(e===null)return null;if(this.Ls?.Kh===e)return this.Ls.Gh;const t=new Vu(e);return this.Ls={Kh:e,Gh:t},t}Zh(){return this.Yh.zOrder?.()??"normal"}}function ao(s){return{ri:s.text(),Ei:s.coordinate(),Vi:s.fixedCoordinate?.(),R:s.textColor(),Z:s.backColor(),It:s.visible?.()??!0,pi:s.tickVisible?.()??!0}}class Ku{constructor(e,t){this.Xt=new Za,this.ta=e,this.ia=t}Tt(){return this.Xt.ht({nn:this.ia.nn(),...ao(this.ta)}),this.Xt}}class Gu extends hi{constructor(e,t){super(),this.ta=e,this.Ki=t}Yi(e,t,i){const n=ao(this.ta);i.Z=n.Z,e.R=n.R;const a=2/12*this.Ki.P();i.Ti=a,i.Ri=a,i.Ei=n.Ei,i.Vi=n.Vi,e.ri=n.ri,e.It=n.It,e.pi=n.pi}}class Qu extends no{constructor(e,t){super(e),this.na=null,this.sa=null,this.ea=null,this.ra=null,this.Te=t}dn(){const e=this.Jh.timeAxisViews?.()??[];if(this.na?.Kh===e)return this.na.Gh;const t=this.Te.Qt().Et(),i=e.map(n=>new Ku(n,t));return this.na={Kh:e,Gh:i},i}qn(){const e=this.Jh.priceAxisViews?.()??[];if(this.sa?.Kh===e)return this.sa.Gh;const t=this.Te.Ft(),i=e.map(n=>new Gu(n,t));return this.sa={Kh:e,Gh:i},i}ha(){const e=this.Jh.priceAxisPaneViews?.()??[];if(this.ea?.Kh===e)return this.ea.Gh;const t=e.map(i=>new bn(i));return this.ea={Kh:e,Gh:t},t}aa(){const e=this.Jh.timeAxisPaneViews?.()??[];if(this.ra?.Kh===e)return this.ra.Gh;const t=e.map(i=>new bn(i));return this.ra={Kh:e,Gh:t},t}la(e,t){return this.Jh.autoscaleInfo?.(e,t)??null}}function _s(s,e,t,i){s.forEach(n=>{e(n).forEach(a=>{a.Zh()===t&&i.push(a)})})}function Ss(s){return s.jn()}function Yu(s){return s.ha()}function Ju(s){return s.aa()}const Xu=["Area","Line","Baseline"];class pi extends Du{constructor(e,t,i,n,a){super(e),this.qt=Ei(),this.dr=new Ru(this),this.oa=[],this._a=new Mu(this),this.ua=null,this.ca=null,this.da=null,this.fa=[],this.pa=new $u,this.va=new Map,this.ma=null,this.yn=i,this.wa=t;const o=new Pu(this);if(this.mn=[o],this.pr=new io(o,this,e),Xu.includes(this.wa)&&(this.ua=new Tu(this)),this.Ma(),this.Yh=n(this,this.Qt(),a),this.wa==="Custom"){const l=this.Yh;l.ga&&this.ba(l.ga)}}m(){this.da!==null&&clearTimeout(this.da)}We(e){return this.yn.priceLineColor||e}Ae(e){const t={Le:!0},i=this.Ft();if(this.Qt().Et().Zi()||i.Zi()||this.qt.Zi())return t;const n=this.Qt().Et().Ee(),a=this.Lt();if(n===null||a===null)return t;let o,l;if(e){const u=this.qt.kh();if(u===null)return t;o=u,l=u.$n}else{const u=this.qt.Hn(n.bi(),-1);if(u===null||(o=this.qt.Mh(u.$n),o===null))return t;l=u.$n}const c=o.Wt[3],d=this.Sa().Sh(l,{Wt:o}),h=i.Nt(c,a.Wt);return{Le:!1,Mt:c,ri:i.Ji(c,a.Wt),qe:i.xa(c),Ye:i.Ca(c,a.Wt),R:d.sh,Ei:h,$n:l}}Sa(){return this.ca!==null||(this.ca=new Fu(this)),this.ca}N(){return this.yn}vr(e){const t=this.Qt(),{priceScaleId:i,visible:n,priceFormat:a}=e;i!==void 0&&i!==this.yn.priceScaleId&&t.ya(this,i),n!==void 0&&n!==this.yn.visible&&t.Pa();const o=e.conflationThresholdFactor!==void 0;Me(this.yn,e),Object.prototype.hasOwnProperty.call(e,"autoscaleInfoProvider")&&e.autoscaleInfoProvider===void 0&&(this.yn.autoscaleInfoProvider=void 0),o&&(this.va.clear(),this.Qt().mr()),a!==void 0&&(this.Ma(),t.ka()),t.Ta(this),t.Ra(),this.Yh.Pt("options")}ht(e,t){this.qt.ht(e),this.va.clear();const i=this.Qt().Et().N();i.enableConflation&&i.precomputeConflationOnInit&&this.Da(i.precomputeConflationPriority),this.Ia(),this.ua!==null&&(t&&t.Va?this.ua.De():e.length===0&&this.ua.Re());const n=this.Qt().Ks(this);this.Qt().Ba(n),this.Qt().Ta(this),this.Qt().Ra(),this.Qt().mr()}Ia(){this.Yh.Pt("data")}Ea(e){const t=new Iu(this,e);return this.oa.push(t),this.Qt().Ta(this),t}Aa(e){const t=this.oa.indexOf(e);t!==-1&&this.oa.splice(t,1),this.Qt().Ta(this)}La(){return this.oa}bh(){return this.wa}Lt(){const e=this.za();return e===null?null:{Wt:e.Wt[3],Oa:e.wt}}za(){const e=this.Qt().Et().Ee();if(e===null)return null;const t=e.Na();return this.qt.Hn(t,1)}Un(){return this.qt}ba(e){this.ma=e,this.va.clear()}Fa(){return!!this.Qt().Et().N().enableConflation&&this.Wa()>1}Rr(e){if(!this.Fa())return;const t=this.Wa();if(!this.va.has(t))return;const i=this.wa==="Custom",n=i&&this.ma||void 0,a=i&&this.Yh.Ha?c=>{const d=c,h=this.Yh.Ha(d);return Array.isArray(h)?h:[typeof h=="number"?h:0]}:void 0,o=this.pa.Rr(this.qt.Bh(),e,t,n,i,a),l=Ei();l.ht(o),this.va.set(t,l)}Ua(){const e=this.Qt().Et().N().enableConflation;if(this.wa==="Custom"&&this.ma===null)return this.qt;if(!e)return this.qt;const t=this.Wa(),i=this.va.get(t);return i||(this.$a(t),this.va.get(t)??this.qt)}ja(e){const t=this.qt.Mh(e);return t===null?null:this.wa==="Bar"||this.wa==="Candlestick"||this.wa==="Custom"?{jr:t.Wt[0],qr:t.Wt[1],Yr:t.Wt[2],Kr:t.Wt[3]}:t.Wt[3]}qa(e){const t=[];_s(this.fa,Ss,"top",t);const i=this.ua;return i!==null&&i.It()&&(this.da===null&&i.Ve()&&(this.da=setTimeout(()=>{this.da=null,this.Qt().Ya()},0)),i.Ie(),t.unshift(i)),t}jn(){const e=[];this.Ka()||e.push(this._a),e.push(this.Yh,this.dr);const t=this.oa.map(i=>i.wr());return e.push(...t),_s(this.fa,Ss,"normal",e),e}Ga(){const e=this.Yh.Ga?.()??null;if(e===null)return null;const t=[];this.Ka()||t.push(this._a),t.push(...e.Za),_s(this.fa,Ss,"normal",t);const i=[];i.push(...e.qa,this.dr);const n=this.oa.map(a=>a.wr());return i.push(...n),{Za:t,qa:i}}Xa(){return this.Ja(Ss,"bottom")}Qa(e){return this.Ja(Yu,e)}tl(e){return this.Ja(Ju,e)}il(e,t){return this.fa.map(i=>i.Qs(e,t)).filter(i=>i!==null)}cn(){return[this.pr,...this.oa.map(e=>e.Mr())]}qn(e,t){if(t!==this.hn&&!this.Ka())return[];const i=[...this.mn];for(const n of this.oa)i.push(n.gr());return this.fa.forEach(n=>{i.push(...n.qn())}),i}dn(){const e=[];return this.fa.forEach(t=>{e.push(...t.dn())}),e}la(e,t){if(this.yn.autoscaleInfoProvider!==void 0){const i=this.yn.autoscaleInfoProvider(()=>{const n=this.nl(e,t);return n===null?null:n.sr()});return Qs.er(i)}return this.nl(e,t)}Kh(){const e=this.yn.priceFormat;return e.base??1/e.minMove}sl(){return this.el}Nn(){this.Yh.Pt();for(const e of this.mn)e.Pt();for(const e of this.oa)e.Pt();this.dr.Pt(),this._a.Pt(),this.ua?.Pt(),this.fa.forEach(e=>e.Nn())}Ft(){return P(super.Ft())}At(e){if(!((this.wa==="Line"||this.wa==="Area"||this.wa==="Baseline")&&this.yn.crosshairMarkerVisible))return null;const t=this.qt.Mh(e);return t===null?null:{Mt:t.Wt[3],ft:this.rl(),Ht:this.hl(),Ot:this.al(),zt:this.ll(e)}}He(){return this.yn.title}It(){return this.yn.visible}ol(e){this.fa.push(new Qu(e,this))}_l(e){this.fa=this.fa.filter(t=>t.Qh()!==e)}ul(){if(this.wa==="Custom")return e=>this.Yh.Ha(e)}cl(){if(this.wa==="Custom")return e=>this.Yh.dl(e)}fl(){return this.qt.Lh()}Ka(){return!ui(this.Ft().pl())}nl(e,t){if(!rs(e)||!rs(t)||this.qt.Zi())return null;const i=this.wa==="Line"||this.wa==="Area"||this.wa==="Baseline"||this.wa==="Histogram"?[3]:[2,1],n=this.qt.Eh(e,t,i);let a=n!==null?new ye(n.Uh,n.$h):null,o=null;if(this.bh()==="Histogram"){const l=this.yn.base,c=new ye(l,l);a=a!==null?a.Ss(c):c}return this.fa.forEach(l=>{const c=l.la(e,t);if(c?.priceRange){const d=new ye(c.priceRange.minValue,c.priceRange.maxValue);a=a!==null?a.Ss(d):d}c?.margins&&(o=c.margins)}),new Qs(a,o)}rl(){switch(this.wa){case"Line":case"Area":case"Baseline":return this.yn.crosshairMarkerRadius}return 0}hl(){switch(this.wa){case"Line":case"Area":case"Baseline":{const e=this.yn.crosshairMarkerBorderColor;if(e.length!==0)return e}}return null}al(){switch(this.wa){case"Line":case"Area":case"Baseline":return this.yn.crosshairMarkerBorderWidth}return 0}ll(e){switch(this.wa){case"Line":case"Area":case"Baseline":{const t=this.yn.crosshairMarkerBackgroundColor;if(t.length!==0)return t}}return this.Sa().Sh(e).sh}Ma(){switch(this.yn.priceFormat.type){case"custom":{const e=this.yn.priceFormat.formatter;this.el={format:e,formatTickmarks:this.yn.priceFormat.tickmarksFormatter??(t=>t.map(e))};break}case"volume":this.el=new ju(this.yn.priceFormat.precision);break;case"percent":this.el=new so(this.yn.priceFormat.precision);break;default:{const e=Math.pow(10,this.yn.priceFormat.precision);this.el=new mi(e,this.yn.priceFormat.minMove*e)}}this.hn!==null&&this.hn.vl()}Ja(e,t){const i=[];return _s(this.fa,e,t,i),i}Wa(){const{ml:e,wl:t,Ml:i}=this.gl();return this.pa.Sr(e,t,i)}gl(){const e=this.Qt().Et(),t=e.ml(),i=window.devicePixelRatio||1,n=e.N().conflationThresholdFactor;return{ml:t,wl:i,Ml:this.yn.conflationThresholdFactor??n??1}}bl(e){const t=this.qt.Bh();let i;if(this.wa==="Custom"&&this.ma!==null){const a=this.ul();if(!a)throw new Error(Au);i=this.pa.Cr(t,e,this.ma,!0,o=>a(o))}else i=this.pa.Cr(t,e);const n=Ei();return n.ht(i),n}$a(e){const t=this.bl(e);this.va.set(e,t)}Da(e){if(this.wa==="Custom"&&(this.ma===null||!this.ul()))return;this.va.clear();const t=this.Qt().Et().Sl();for(const i of t){const n=()=>{this.xl(i)},a=typeof window=="object"&&window||typeof self=="object"&&self;a?.yl?.Cl?a.yl.Cl(()=>{n()},{se:e}):Promise.resolve().then(()=>n())}}xl(e){if(this.va.has(e)||this.qt.Bh().length===0)return;const t=this.bl(e);this.va.set(e,t)}}const Zu=[3],em=[0,1,2,3];class tm{constructor(e){this.yn=e}Pl(e,t,i){let n=e;if(this.yn.mode===0)return n;const a=i.kn(),o=a.Lt();if(o===null)return n;const l=a.Nt(e,o),c=i.kl().filter(h=>h instanceof pi).reduce((h,u)=>{if(i.Gs(u)||!u.It())return h;const m=u.Ft(),x=u.Un();if(m.Zi()||!x.ze(t))return h;const b=x.Mh(t);if(b===null)return h;const f=Ge(u.Lt()),v=this.yn.mode===3?em:Zu;return h.concat(v.map(p=>m.Nt(b.Wt[p],f.Wt)))},[]);if(c.length===0)return n;c.sort((h,u)=>Math.abs(h-l)-Math.abs(u-l));const d=c[0];return n=a.Tn(d,o),n}}function St(s,e,t){return Math.min(Math.max(s,e),t)}function ks(s,e,t){return e-s<=t}class sm extends Ue{constructor(){super(...arguments),this.qt=null}ht(e){this.qt=e}et({context:e,bitmapSize:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(this.qt===null)return;const a=Math.max(1,Math.floor(i));e.lineWidth=a,function(o,l){o.save(),o.lineWidth%2&&o.translate(.5,.5),l(),o.restore()}(e,()=>{const o=P(this.qt);if(o.Tl){e.strokeStyle=o.Rl,Xe(e,o.Dl),e.beginPath();for(const l of o.Il){const c=Math.round(l.Vl*i);e.moveTo(c,-a),e.lineTo(c,t.height+a)}e.stroke()}if(o.Bl){e.strokeStyle=o.El,Xe(e,o.Al),e.beginPath();for(const l of o.Ll){const c=Math.round(l.Vl*n);e.moveTo(-a,c),e.lineTo(t.width+a,c)}e.stroke()}})}}class im{constructor(e){this.Xt=new sm,this.xt=!0,this.yt=e}Pt(){this.xt=!0}Tt(){if(this.xt){const e=this.yt.Qt().N().grid,t={Bl:e.horzLines.visible,Tl:e.vertLines.visible,El:e.horzLines.color,Rl:e.vertLines.color,Al:e.horzLines.style,Dl:e.vertLines.style,Ll:this.yt.kn().zl(),Il:(this.yt.Qt().Et().zl()||[]).map(i=>({Vl:i.coord}))};this.Xt.ht(t),this.xt=!1}return this.Xt}}class rm{constructor(e){this.Yh=new im(e)}wr(){return this.Yh}}const Ti={Ol:4,Nl:1e-4};function wt(s,e){const t=100*(s-e)/e;return e<0?-t:t}function nm(s,e){const t=wt(s.Je(),e),i=wt(s.Qe(),e);return new ye(t,i)}function Yt(s,e){const t=100*(s-e)/e+100;return e<0?-t:t}function am(s,e){const t=Yt(s.Je(),e),i=Yt(s.Qe(),e);return new ye(t,i)}function Js(s,e){const t=Math.abs(s);if(t<1e-15)return 0;const i=Math.log10(t+e.Nl)+e.Ol;return s<0?-i:i}function Jt(s,e){const t=Math.abs(s);if(t<1e-15)return 0;const i=Math.pow(10,t-e.Ol)-e.Nl;return s<0?-i:i}function Wt(s,e){if(s===null)return null;const t=Js(s.Je(),e),i=Js(s.Qe(),e);return new ye(t,i)}function Nt(s,e){if(s===null)return null;const t=Jt(s.Je(),e),i=Jt(s.Qe(),e);return new ye(t,i)}function Ri(s){if(s===null)return Ti;const e=Math.abs(s.Qe()-s.Je());if(e>=1||e<1e-15)return Ti;const t=Math.ceil(Math.abs(Math.log10(e))),i=Ti.Ol+t;return{Ol:i,Nl:1/Math.pow(10,i)}}class Pi{constructor(e,t){if(this.Fl=e,this.Wl=t,function(i){if(i<0)return!1;if(i>1e18)return!0;for(let n=i;n>1;n/=10)if(n%10!=0)return!1;return!0}(this.Fl))this.Hl=[2,2.5,2];else{this.Hl=[];for(let i=this.Fl;i!==1;){if(i%2==0)this.Hl.push(2),i/=2;else{if(i%5!=0)throw new Error("unexpected base");this.Hl.push(2,2.5),i/=5}if(this.Hl.length>100)throw new Error("something wrong with base")}}}Ul(e,t,i){const n=this.Fl===0?0:1/this.Fl;let a=Math.pow(10,Math.max(0,Math.ceil(Math.log10(e-t)))),o=0,l=this.Wl[0];for(;;){const u=ks(a,n,1e-14)&&a>n+1e-14,m=ks(a,i*l,1e-14),x=ks(a,1,1e-14);if(!(u&&m&&x))break;a/=l,l=this.Wl[++o%this.Wl.length]}if(a<=n+1e-14&&(a=n),a=Math.max(1,a),this.Hl.length>0&&(c=a,d=1,h=1e-14,Math.abs(c-d)n+1e-14;)a/=l,l=this.Hl[++o%this.Hl.length];var c,d,h;return a}}class gn{constructor(e,t,i,n){this.$l=[],this.Ki=e,this.Fl=t,this.jl=i,this.ql=n}Ul(e,t){if(eb.no),x=this.Ki.so(m);for(let b=0;b=n?1:-1;let u=null,m=0;for(let x=i-d;x>n;x-=t){const b=this.ql(x,e,!0);u!==null&&Math.abs(b-u)o||(m0&&l[0].Vl-c.Vl0&&d.Vl-l[l.length-1].VlP(e.ln())-P(t.ln()))}var vn;(function(s){s[s.Normal=0]="Normal",s[s.Logarithmic=1]="Logarithmic",s[s.Percentage=2]="Percentage",s[s.IndexedTo100=3]="IndexedTo100"})(vn||(vn={}));const yn=new so,wn=new mi(100,1);class om{constructor(e,t,i,n,a){this.oo=0,this._o=null,this.rr=null,this.uo=null,this.co={do:!1,fo:null},this.po=!1,this.vo=0,this.mo=0,this.wo=new le,this.Mo=new le,this.bo=[],this.So=null,this.xo=null,this.Co=null,this.yo=null,this.Po=null,this.el=wn,this.ko=Ri(null),this.To=e,this.yn=t,this.Ro=i,this.Do=n,this.Io=a,this.Vo=new gn(this,100,this.Bo.bind(this),this.Eo.bind(this))}pl(){return this.To}N(){return this.yn}vr(e){if(Me(this.yn,e),this.vl(),e.mode!==void 0&&this.Ao({_e:e.mode}),e.scaleMargins!==void 0){const t=_e(e.scaleMargins.top),i=_e(e.scaleMargins.bottom);if(t<0||t>1)throw new Error(`Invalid top margin - expect value between 0 and 1, given=${t}`);if(i<0||i>1)throw new Error(`Invalid bottom margin - expect value between 0 and 1, given=${i}`);if(t+i>1)throw new Error(`Invalid margins - sum of margins must be less than 1, given=${t+i}`);this.Lo(),this.Co=null}}zo(){return this.yn.autoScale}Oo(){return this.po}ho(){return this.yn.mode===1}je(){return this.yn.mode===2}No(){return this.yn.mode===3}lo(){return this.ko}_e(){return{hs:this.yn.autoScale,Fo:this.yn.invertScale,_e:this.yn.mode}}Ao(e){const t=this._e();let i=null;e.hs!==void 0&&(this.yn.autoScale=e.hs),e._e!==void 0&&(this.yn.mode=e._e,e._e!==2&&e._e!==3||(this.yn.autoScale=!0),this.co.do=!1),t._e===1&&e._e!==t._e&&(function(a,o){if(a===null)return!1;const l=Jt(a.Je(),o),c=Jt(a.Qe(),o);return isFinite(l)&&isFinite(c)}(this.rr,this.ko)?(i=Nt(this.rr,this.ko),i!==null&&this.Wo(i)):this.yn.autoScale=!0),e._e===1&&e._e!==t._e&&(i=Wt(this.rr,this.ko),i!==null&&this.Wo(i));const n=t._e!==this.yn.mode;n&&(t._e===2||this.je())&&this.vl(),n&&(t._e===3||this.No())&&this.vl(),e.Fo!==void 0&&t.Fo!==e.Fo&&(this.yn.invertScale=e.Fo,this.Ho()),this.Mo.p(t,this._e())}Uo(){return this.Mo}P(){return this.Ro.fontSize}$t(){return this.oo}$o(e){this.oo!==e&&(this.oo=e,this.Lo(),this.Co=null)}jo(){if(this._o)return this._o;const e=this.$t()-this.qo()-this.Yo();return this._o=e,e}ar(){return this.Ko(),this.rr}Wo(e,t){const i=this.rr;(t||i===null&&e!==null||i!==null&&!i.Ze(e))&&(this.Co=null,this.rr=e)}Go(e){this.Wo(e),this.Zo(e!==null)}Zi(){return this.Ko(),this.oo===0||!this.rr||this.rr.Zi()}Xo(e){return this.Fo()?e:this.$t()-1-e}Nt(e,t){return this.je()?e=wt(e,t):this.No()&&(e=Yt(e,t)),this.Eo(e,t)}Jo(e,t,i){this.Ko();const n=this.Yo(),a=P(this.ar()),o=a.Je(),l=a.Qe(),c=this.jo()-1,d=this.Fo(),h=c/(l-o),u=i===void 0?0:i.from,m=i===void 0?e.length:i.to,x=this.Qo();for(let b=u;be.Nn())}Xl(){return this.yn.ensureEdgeTickMarksVisible&&this.zo()}Ql(){return this.P()/2}vl(){this.Co=null;let e=1/0;this.So=null;for(const i of this.bo)i.ln()Js(e,this.ko):null}C_(e,t,i){return t===void 0?(i===void 0&&(i=this.sl()),i.format(e)):t(e)}y_(e,t,i){return t===void 0?(i===void 0&&(i=this.sl()),i.formatTickmarks(e)):t(e)}cr(e,t){return this.C_(e,this.Do.priceFormatter,t)}M_(e,t){const i=this.Do.priceFormatter;return this.y_(e,this.Do.tickmarksPriceFormatter??(i?n=>n.map(i):void 0),t)}m_(e,t){return this.C_(e,this.Do.percentageFormatter,t)}w_(e,t){const i=this.Do.percentageFormatter;return this.y_(e,this.Do.tickmarksPercentageFormatter??(i?n=>n.map(i):void 0),t)}}function Nn(s){return s instanceof pi}class Zi{constructor(e,t){this.bo=[],this.P_=new Map,this.oo=0,this.k_=0,this.T_=1,this.xo=null,this.R_=null,this.D_=!1,this.I_=new le,this.fa=[],this.ia=e,this.sn=t,this.V_=new rm(this);const i=t.N();this.B_=this.E_("left",i.leftPriceScale),this.A_=this.E_("right",i.rightPriceScale),this.B_.Uo().i(this.L_.bind(this,this.B_),this),this.A_.Uo().i(this.L_.bind(this,this.A_),this),this.z_(i)}z_(e){if(e.leftPriceScale&&this.B_.vr(e.leftPriceScale),e.rightPriceScale&&this.A_.vr(e.rightPriceScale),e.localization&&(this.B_.vl(),this.A_.vl()),e.overlayPriceScales){const t=Array.from(this.P_.values());for(const i of t){const n=P(i[0].Ft());n.vr(e.overlayPriceScales),e.localization&&n.vl()}}}O_(e){switch(e){case"left":return this.B_;case"right":return this.A_}return this.P_.has(e)?_e(this.P_.get(e))[0].Ft():null}m(){this.Qt().N_().u(this),this.B_.Uo().u(this),this.A_.Uo().u(this),this.bo.forEach(e=>{e.m&&e.m()}),this.fa=this.fa.filter(e=>{const t=e.Qh();return t.detached&&t.detached(),!1}),this.I_.p()}F_(){return this.T_}W_(e){this.T_=e}Qt(){return this.sn}nn(){return this.k_}$t(){return this.oo}H_(e){this.k_=e,this.U_()}$o(e){this.oo=e,this.B_.$o(e),this.A_.$o(e),this.bo.forEach(t=>{if(this.Gs(t)){const i=t.Ft();i!==null&&i.$o(e)}}),this.U_()}j_(e){this.D_=e}q_(){return this.D_}Y_(){return this.bo.filter(Nn)}kl(){return this.bo}Gs(e){const t=e.Ft();return t===null||this.B_!==t&&this.A_!==t}h_(e,t,i){this.K_(e,t,i?e.ln():this.bo.length)}l_(e,t){const i=this.bo.indexOf(e);me(i!==-1,"removeDataSource: invalid data source"),this.bo.splice(i,1),t||this.bo.forEach((o,l)=>o._n(l));const n=P(e.Ft()).pl();if(this.P_.has(n)){const o=_e(this.P_.get(n)),l=o.indexOf(e);l!==-1&&(o.splice(l,1),o.length===0&&this.P_.delete(n))}const a=e.Ft();a&&a.kl().indexOf(e)>=0&&(a.l_(e),this.G_(a)),this.Z_()}Xs(e){return e===this.B_?"left":e===this.A_?"right":"overlay"}X_(){return this.B_}J_(){return this.A_}Q_(e,t){e.u_(t)}tu(e,t){e.c_(t),this.U_()}iu(e){e.d_()}nu(e,t){e.f_(t)}su(e,t){e.p_(t),this.U_()}eu(e){e.v_()}U_(){this.bo.forEach(e=>{e.Nn()})}kn(){const[e,t]=this.ru();let i=null;return e.N().visible&&e.kl().length!==0?i=e:t.N().visible&&t.kl().length!==0?i=t:this.bo.length!==0&&(i=this.bo[0].Ft()),i===null&&(i=this.Zs()??e),i}Zs(){const[e,t]=this.ru();return e.N().visible?e:t.N().visible?t:null}G_(e){e!==null&&e.zo()&&this.hu(e)}au(e){const t=this.ia.Ee();e.Ao({hs:!0}),t!==null&&e.b_(t),this.U_()}lu(){this.hu(this.B_),this.hu(this.A_)}ou(){this.G_(this.B_),this.G_(this.A_),this.bo.forEach(e=>{this.Gs(e)&&this.G_(e.Ft())}),this.U_(),this.sn.mr()}Dt(){return this.xo===null&&(this.xo=oo(this.bo)),this.xo}_u(){const e=this.Dt(),t=this.sn.cu()?.uu,i=this.sn.N().hoveredSeriesOnTop,n=this.R_;if(n!==null&&n.Kh===e&&n.du===t&&n.fu===i)return n.pu;const a=function(o,l,c){if(!c)return o;const d=o.indexOf(l);if(d===-1||d===o.length-1)return o;const h=[];for(let u=0;un._n(a)),this.Z_();for(const n of[this.B_,this.A_])n.a_(),n.vl();this.sn.mr()}Vt(){return this.Dt().filter(Nn)}mu(){return this.I_}wu(){return this.V_}ol(e){this.fa.push(new Hu(e))}_l(e){this.fa=this.fa.filter(t=>t.Qh()!==e),e.detached&&e.detached(),this.sn.mr()}Mu(){return this.fa}il(e,t){return this.fa.map(i=>i.Qs(e,t)).filter(i=>i!==null)}hu(e){const t=e.g_();if(t&&t.length>0&&!this.ia.Zi()){const i=this.ia.Ee();i!==null&&e.b_(i)}e.Nn()}K_(e,t,i){let n=this.O_(t);if(n===null&&(n=this.E_(t,this.sn.N().overlayPriceScales)),this.bo.splice(i,0,e),!ui(t)){const a=this.P_.get(t)||[];a.push(e),this.P_.set(t,a)}e._n(i),n.h_(e),e.un(n),this.G_(n),this.Z_()}Z_(){this.xo=null,this.R_=null}ru(){return this.sn.N().defaultVisiblePriceScaleId==="left"?[this.B_,this.A_]:[this.A_,this.B_]}L_(e,t,i){t._e!==i._e&&this.hu(e)}E_(e,t){const i={visible:!0,autoScale:!0,...$e(t)},n=new om(e,i,this.sn.N().layout,this.sn.N().localization,this.sn.Xi());return n.$o(this.$t()),n}}function er(s,e){return e===null||s.se===2&&e.se!==2||(e.se!==2||s.se===2)&&s.ne!==e.ne&&s.ne= left"),this.Ru=e,this.Du=t}Na(){return this.Ru}bi(){return this.Du}Iu(){return this.Du-this.Ru+1}ze(e){return this.Ru<=e&&e<=this.Du}Ze(e){return this.Ru===e.Na()&&this.Du===e.bi()}}function jn(s,e){return s===null||e===null?s===e:s.Ze(e)}class um{constructor(){this.Vu=new Map,this.Ls=null,this.Bu=!1}Eu(e){this.Bu=e,this.Ls=null}Au(e,t){this.Lu(t),this.Ls=null;for(let i=t;i{e<=i[0].index?t.push(n):i.splice(ht(i,e,a=>a.index!t||i.has(o.index);for(const o of Array.from(this.Vu.keys()).sort((l,c)=>c-l)){if(!this.Vu.get(o))continue;const l=n;n=[];const c=l.length;let d=0;const h=_e(this.Vu.get(o)),u=h.length;let m=1/0,x=-1/0;for(let b=0;b=e&&v-x>=e&&a(f))n.push(f),x=v;else if(this.Bu)return l}for(;de.weight?s:e}class pm{constructor(e,t,i,n){this.k_=0,this.qu=null,this.Yu=[],this.Po=null,this.yo=null,this.Ku=new um,this.Gu=new Map,this.Zu=kt.ju(),this.Xu=!0,this.Ju=new le,this.Qu=new le,this.tc=new le,this.nc=null,this.sc=null,this.ec=new Map,this.rc=-1,this.hc=[],this.ac=1,this.yn=t,this.Do=i,this.lc=t.rightOffset,this.oc=t.barSpacing,this.sn=e,this._c(t),this.Pu=n,this.uc(),this.Ku.Eu(t.uniformDistribution),this.cc(),this.dc()}N(){return this.yn}fc(e){Me(this.Do,e),this.vc(),this.uc()}vr(e,t){Me(this.yn,e),this.yn.fixLeftEdge&&this.mc(),this.yn.fixRightEdge&&this.wc(),e.barSpacing!==void 0&&this.sn.Ms(e.barSpacing),e.rightOffset!==void 0&&this.sn.gs(e.rightOffset),this._c(e),e.minBarSpacing===void 0&&e.maxBarSpacing===void 0||this.sn.Ms(e.barSpacing??this.oc),e.ignoreWhitespaceIndices!==void 0&&e.ignoreWhitespaceIndices!==this.yn.ignoreWhitespaceIndices&&this.dc(),this.vc(),this.uc(),e.enableConflation===void 0&&e.conflationThresholdFactor===void 0||this.cc(),this.tc.p()}Rn(e){return this.Yu[e]?.time??null}en(e){return this.Yu[e]??null}Mc(e,t){if(this.Yu.length<1)return null;if(this.Pu.key(e)>this.Pu.key(this.Yu[this.Yu.length-1].time))return t?this.Yu.length-1:null;const i=ht(this.Yu,this.Pu.key(e),(n,a)=>this.Pu.key(n.time)0}Ee(){return this.bc(),this.Zu.Uu()}Sc(){return this.bc(),this.Zu.$u()}xc(){const e=this.Ee();if(e===null)return null;const t={from:e.Na(),to:e.bi()};return this.Cc(t)}Cc(e){const t=Math.round(e.from),i=Math.round(e.to),n=P(this.yc()),a=P(this.Pc());return{from:P(this.en(Math.max(n,t))),to:P(this.en(Math.min(a,i)))}}kc(e){return{from:P(this.Mc(e.from,!0)),to:P(this.Mc(e.to,!0))}}nn(){return this.k_}H_(e){if(!isFinite(e)||e<=0||this.k_===e)return;const t=this.Sc(),i=this.k_;if(this.k_=e,this.Xu=!0,this.yn.lockVisibleTimeRangeOnResize&&i!==0){const n=this.oc*e/i;this.oc=n}if(this.yn.fixLeftEdge&&t!==null&&t.Na()<=0){const n=i-e;this.lc-=Math.round(n/this.oc)+1,this.Xu=!0}this.Tc(),this.Rc()}jt(e){if(this.Zi()||!rs(e))return 0;const t=this.Dc()+this.lc-e;return this.k_-(t+.5)*this.oc-1}Ic(e,t){const i=this.Dc(),n=t===void 0?0:t.from,a=t===void 0?e.length:t.to;for(let o=n;ot/2&&!h?f.needAlignCoordinate=!1:f.needAlignCoordinate=u&&b.index<=c||m&&b.index>=d,x++}return this.hc.length=x,this.sc=this.hc,this.hc}Wc(){let e;this.Xu=!0,this.Ms(this.yn.barSpacing),e=this.yn.rightOffsetPixels!==void 0?this.yn.rightOffsetPixels/this.ml():this.yn.rightOffset,this.gs(e)}Hc(e){this.Xu=!0,this.qu=e,this.Rc(),this.mc()}Uc(e,t){const i=this.Bc(e),n=this.ml(),a=n+t*(n/10);this.Ms(a),this.yn.rightBarStaysOnScroll||this.gs(this.Oc()+(i-this.Bc(e)))}u_(e){this.Po&&this.v_(),this.yo===null&&this.nc===null&&(this.Zi()||(this.yo=e,this.$c()))}c_(e){if(this.nc===null)return;const t=St(this.k_-e,0,this.k_),i=St(this.k_-P(this.yo),0,this.k_);t!==0&&i!==0&&this.Ms(this.nc.ml*t/i)}d_(){this.yo!==null&&(this.yo=null,this.jc())}f_(e){this.Po===null&&this.nc===null&&(this.Zi()||(this.Po=e,this.$c()))}p_(e){if(this.Po===null)return;const t=(this.Po-e)/this.ml();this.lc=P(this.nc).Oc+t,this.Xu=!0,this.Rc()}v_(){this.Po!==null&&(this.Po=null,this.jc())}qc(){this.Yc(this.yn.rightOffset)}Yc(e,t=400){if(!isFinite(e))throw new RangeError("offset is required and must be finite number");if(!isFinite(t)||t<=0)throw new RangeError("animationDuration (optional) must be finite positive number");const i=this.lc,n=performance.now();this.sn.ps({Kc:a=>(a-n)/t>=1,Gc:a=>{const o=(a-n)/t;return o>=1?e:i+(e-i)*o}})}Pt(e,t){this.Xu=!0,this.Yu=e,this.Ku.Au(e,t),this.Rc()}Zc(){return this.Ju}Xc(){return this.Qu}Jc(){return this.tc}Dc(){return this.qu||0}Qc(e,t){const i=e.Iu(),n=t&&this.yn.rightOffsetPixels||0;this.zc((this.k_-n)/i),this.lc=e.bi()-this.Dc(),t&&(this.lc=n?n/this.ml():this.yn.rightOffset),this.Rc(),this.Xu=!0,this.sn.Lc(),this.sn.mr()}td(){const e=this.yc(),t=this.Pc();if(e===null||t===null)return;const i=!this.yn.rightOffsetPixels&&this.yn.rightOffset||0;this.Qc(new Xt(e,t+i),!0)}nd(e){const t=new Xt(e.from,e.to);this.Qc(t)}rn(e){return this.Do.timeFormatter!==void 0?this.Do.timeFormatter(e.originalTime):this.Pu.formatHorzItem(e.time)}dc(){if(!this.yn.ignoreWhitespaceIndices)return;this.ec.clear();const e=this.sn.Jn();for(const t of e)for(const i of t.fl())this.ec.set(i,!0);this.rc++}sd(){return this.ac}Sl(){const e=1/(window.devicePixelRatio||1),t=this.yn.minBarSpacing;if(t>=e)return[1];const i=[1];let n=2;for(;n<=512;)t0?this.yn.maxBarSpacing:.5*this.k_}ad(){return this.yn.fixLeftEdge&&this.yn.fixRightEdge&&this.Yu.length!==0?this.k_/this.Yu.length:this.yn.minBarSpacing}cc(){if(!this.yn.enableConflation)return void(this.ac=1);const e=1/(window.devicePixelRatio||1)*(this.yn.conflationThresholdFactor??1);if(this.oc>=e)return void(this.ac=1);const t=e/this.oc,i=Math.pow(2,Math.floor(Math.log2(t)));this.ac=Math.min(i,512)}Rc(){const e=this.od();e!==null&&this.lct&&(this.lc=t,this.Xu=!0)}od(){const e=this.yc(),t=this.qu;return e===null||t===null?null:e-t-1+(this.yn.fixLeftEdge?this.k_/this.oc:Math.min(2,this.Yu.length))}_d(){return this.yn.fixRightEdge?0:this.k_/this.oc-Math.min(2,this.Yu.length)}$c(){this.nc={ml:this.ml(),Oc:this.Oc()}}jc(){this.nc=null}Fc(e){let t=this.Gu.get(e.weight);return t===void 0&&(t=new hm(i=>this.ud(i),this.Pu),this.Gu.set(e.weight,t)),t.ku(e)}ud(e){return this.Pu.formatTickmark(e,this.Do)}hd(e){const t=this.Zu;this.Zu=e,jn(t.Uu(),this.Zu.Uu())||this.Ju.p(),jn(t.$u(),this.Zu.$u())||this.Qu.p(),this.rd()}rd(){this.sc=null}vc(){this.rd(),this.Gu.clear()}uc(){this.Pu.updateFormatter(this.Do)}mc(){if(!this.yn.fixLeftEdge)return;const e=this.yc();if(e===null)return;const t=this.Ee();if(t===null)return;const i=t.Na()-e;if(i<0){const n=this.lc-i-1;this.gs(n)}this.Tc()}wc(){this.Rc(),this.Tc()}Ec(e){return!this.yn.ignoreWhitespaceIndices||this.ec.get(e)||!1}Ac(e){const t=function*(n){const a=Math.round(n),o=ai)break}return e}_c(e){if(e.rightOffsetPixels!==void 0){const t=e.rightOffsetPixels/(e.barSpacing||this.oc);this.sn.gs(t)}}}var _n,Sn,kn,Lt,Mn;(function(s){s[s.OnTouchEnd=0]="OnTouchEnd",s[s.OnNextTap=1]="OnNextTap"})(_n||(_n={}));class fm{constructor(e,t,i){this.dd=[],this.fd=[],this.pd=null,this.k_=0,this.vd=null,this.md=new le,this.wd=new le,this.Md=null,this.gd=e,this.yn=t,this.Pu=i,this.Io=new du(this.yn.layout.colorParsers),this.bd=new cu(this),this.ia=new pm(this,t.timeScale,this.yn.localization,i),this.Ct=new Nu(this,t.crosshair),this.Sd=new tm(t.crosshair),t.addDefaultPane&&(this.xd(0),this.dd[0].W_(2)),this.Cd=this.yd(0),this.Pd=this.yd(1)}ka(){this.kd(ue.ys())}mr(){this.kd(ue.Cs())}Ya(){this.kd(new ue(1))}Ta(e){const t=this.Td(e);this.kd(t)}cu(){return this.vd}Rd(e){if(this.vd?.uu===e?.uu&&this.vd?.bu?.te===e?.bu?.te&&this.vd?.bu?.ie===e?.bu?.ie&&this.vd?.gu===e?.gu&&this.vd?.ee===e?.ee)return;const t=this.vd;this.vd=e,t!==null&&this.Ta(t.uu),e!==null&&e.uu!==t?.uu&&this.Ta(e.uu)}N(){return this.yn}vr(e){Me(this.yn,e),this.dd.forEach(t=>t.z_(e)),e.timeScale!==void 0&&this.ia.vr(e.timeScale),e.localization!==void 0&&this.ia.fc(e.localization),(e.leftPriceScale||e.rightPriceScale)&&this.md.p(),this.Cd=this.yd(0),this.Pd=this.yd(1),this.ka()}Dd(e,t,i=0){const n=this.dd[i];if(n===void 0)return;if(e==="left")return Me(this.yn,{leftPriceScale:t}),n.z_({leftPriceScale:t}),this.md.p(),void this.ka();if(e==="right")return Me(this.yn,{rightPriceScale:t}),n.z_({rightPriceScale:t}),this.md.p(),void this.ka();const a=this.Id(e,i);a!==null&&(a.Ft.vr(t),this.md.p())}Id(e,t){const i=this.dd[t];if(i===void 0)return null;const n=i.O_(e);return n!==null?{Kn:i,Ft:n}:null}Et(){return this.ia}Gn(){return this.dd}Vd(){return this.Ct}Bd(){return this.wd}Ed(e,t){e.$o(t),this.Lc()}H_(e){this.k_=e,this.ia.H_(this.k_),this.dd.forEach(t=>t.H_(e)),this.Lc()}Ad(e){this.dd.length!==1&&(me(e>=0&&e=0&&eu+m.F_(),0),a=this.dd.reduce((u,m)=>u+m.$t(),0),o=a-30*(this.dd.length-1);t=Math.min(o,Math.max(30,t));const l=n/a,c=i.$t();i.W_(t*l);let d=t-c,h=this.dd.length-1;for(const u of this.dd)if(u!==i){const m=Math.min(o,Math.max(30,u.$t()-d/h));d-=u.$t()-m,h-=1;const x=m*l;u.W_(x)}this.ka()}zd(e,t){me(e>=0&&e=0&&t=0&&e=0&&te.It())),this.pd}Pa(){this.pd=null}Kd(e,t,i,n,a){this.Ct.In(e,t);let o=NaN,l=this.ia.Vc(e,!0);const c=this.ia.Ee();c!==null&&(l=Math.min(Math.max(c.Na(),l),c.bi())),l=this.Ct.Fn(l);const d=n.kn(),h=d.Lt();if(h!==null&&(o=d.Tn(t,h)),o=this.Sd.Pl(o,l,n),this.Ct.An(l,o,n),this.Ya(),!a){const u=co(n,e,t);this.Rd(u&&{uu:u.uu,bu:u.bu,gu:u.gu||null,ee:u.ee}),this.wd.p(this.Ct.Bt(),{x:e,y:t},i)}}Gd(e,t,i){const n=i.kn(),a=n.Lt(),o=n.Nt(e,P(a)),l=this.ia.Mc(t,!0),c=this.ia.jt(P(l));this.Kd(c,o,null,i,!0)}Zd(e){this.Vd().zn(),this.Ya(),e||this.wd.p(null,null,null)}Ra(){const e=this.Ct.Kn();if(e!==null){const t=this.Ct.Bn(),i=this.Ct.En();this.Kd(t,i,null,e)}this.Ct.Nn()}Xd(e,t,i){const n=this.ia.Rn(0);t!==void 0&&i!==void 0&&this.ia.Pt(t,i);const a=this.ia.Rn(0),o=this.ia.Dc(),l=this.ia.Ee();if(l!==null&&n!==null&&a!==null){const c=l.ze(o),d=this.Pu.key(n)>this.Pu.key(a),h=e!==null&&e>o&&!d,u=this.ia.N().allowShiftVisibleRangeOnWhitespaceReplacement,m=c&&(i!==void 0||u)&&this.ia.N().shiftVisibleRangeOnNewBar;if(h&&!m){const x=e-o;this.ia.gs(this.ia.Oc()-x)}}this.ia.Hc(e)}Ba(e){e!==null&&e.ou()}Ks(e){if(function(i){return i instanceof Zi}(e))return e;const t=this.dd.find(i=>i.Dt().includes(e));return t===void 0?null:t}Lc(){this.dd.forEach(e=>e.ou()),this.Ra()}m(){this.dd.forEach(e=>e.m()),this.dd.length=0,this.yn.localization.priceFormatter=void 0,this.yn.localization.percentageFormatter=void 0,this.yn.localization.timeFormatter=void 0}Jd(){return this.bd}Js(){return this.bd.N()}N_(){return this.md}Qd(e,t){const i=this.xd(t);this.tf(e,i),this.fd.push(e),this.Pa(),this.fd.length===1?this.ka():this.mr()}if(e){const t=this.Ks(e),i=this.fd.indexOf(e);me(i!==-1,"Series not found");const n=P(t);this.fd.splice(i,1),n.l_(e),e.m&&e.m(),this.Pa(),this.ia.dc(),this.nf(n)}ya(e,t){const i=P(this.Ks(e));i.l_(e,!0),i.h_(e,t,!0)}td(){const e=ue.Cs();e.us(),this.kd(e)}sf(e){const t=ue.Cs();t.fs(e),this.kd(t)}ws(){const e=ue.Cs();e.ws(),this.kd(e)}Ms(e){const t=ue.Cs();t.Ms(e),this.kd(t)}gs(e){const t=ue.Cs();t.gs(e),this.kd(t)}ps(e){const t=ue.Cs();t.ps(e),this.kd(t)}cs(){const e=ue.Cs();e.cs(),this.kd(e)}ef(){const e=this.yn.defaultVisiblePriceScaleId,t=this.yn.leftPriceScale.visible;return t!==this.yn.rightPriceScale.visible?t?"left":"right":e}rf(e,t){if(me(t>=0,"Index should be greater or equal to 0"),t===this.hf(e))return;const i=P(this.Ks(e));i.l_(e);const n=this.xd(t);this.tf(e,n);let a=!1;i.kl().length===0&&(a=this.nf(i)),a||this.ka()}af(){return this.Pd}$(){return this.Cd}Ut(e){const t=this.Pd,i=this.Cd;if(t===i)return t;if(e=Math.max(0,Math.min(100,Math.round(100*e))),this.Md===null||this.Md.ah!==i||this.Md.oh!==t)this.Md={ah:i,oh:t,lf:new Map};else{const a=this.Md.lf.get(e);if(a!==void 0)return a}const n=this.Io.tt(i,t,e/100);return this.Md.lf.set(e,n),n}_f(e){return this.dd.indexOf(e)}Xi(){return this.Io}uf(){return this.cf()}cf(e){const t=new Zi(this.ia,this);this.dd.push(t);const i=e??this.dd.length-1,n=ue.ys();return n.es(i,{rs:0,hs:!0}),this.kd(n),t}xd(e){return me(e>=0,"Index should be greater or equal to 0"),(e=Math.min(this.dd.length,e))t.Y_().includes(e))}Nd(e,t){const i=new ue(t);if(e!==null){const n=this.dd.indexOf(e);i.es(n,{rs:t})}return i}Td(e,t){return t===void 0&&(t=2),this.Nd(this.Ks(e),t)}kd(e){this.gd&&this.gd(e),this.dd.forEach(t=>t.wu().wr().Pt())}tf(e,t){const i=e.N().priceScaleId,n=i!==void 0?i:this.ef();t.h_(e,n),ui(n)||e.vr(e.N())}yd(e){const t=this.yn.layout;return t.background.type==="gradient"?e===0?t.background.topColor:t.background.bottomColor:t.background.color}nf(e){return!e.q_()&&e.kl().length===0&&this.dd.length>1&&(this.dd.splice(this._f(e),1),this.ka(),!0)}}function ho(s){if(s>=1)return 0;let e=0;for(;e<8;e++){const t=Math.round(s);if(Math.abs(t-s)<1e-8)return e;s*=10}return e}function tr(s){return!Rt(s)&&!fs(s)}function uo(s){return Rt(s)}(function(s){s[s.Disabled=0]="Disabled",s[s.Continuous=1]="Continuous",s[s.OnDataUpdate=2]="OnDataUpdate"})(Sn||(Sn={})),function(s){s[s.LastBar=0]="LastBar",s[s.LastVisible=1]="LastVisible"}(kn||(kn={})),function(s){s.Solid="solid",s.VerticalGradient="gradient"}(Lt||(Lt={})),function(s){s[s.Year=0]="Year",s[s.Month=1]="Month",s[s.DayOfMonth=2]="DayOfMonth",s[s.Time=3]="Time",s[s.TimeWithSeconds=4]="TimeWithSeconds"}(Mn||(Mn={}));const Cn=s=>s.getUTCFullYear();function xm(s,e,t){return e.replace(/yyyy/g,(i=>De(Cn(i),4))(s)).replace(/yy/g,(i=>De(Cn(i)%100,2))(s)).replace(/MMMM/g,((i,n)=>new Date(i.getUTCFullYear(),i.getUTCMonth(),1).toLocaleString(n,{month:"long"}))(s,t)).replace(/MMM/g,((i,n)=>new Date(i.getUTCFullYear(),i.getUTCMonth(),1).toLocaleString(n,{month:"short"}))(s,t)).replace(/MM/g,(i=>De((n=>n.getUTCMonth()+1)(i),2))(s)).replace(/dd/g,(i=>De((n=>n.getUTCDate())(i),2))(s))}class mo{constructor(e="yyyy-MM-dd",t="default"){this.df=e,this.ff=t}ku(e){return xm(e,this.df,this.ff)}}class bm{constructor(e){this.pf=e||"%h:%m:%s"}ku(e){return this.pf.replace("%h",De(e.getUTCHours(),2)).replace("%m",De(e.getUTCMinutes(),2)).replace("%s",De(e.getUTCSeconds(),2))}}const gm={vf:"yyyy-MM-dd",mf:"%h:%m:%s",wf:" ",Mf:"default"};class vm{constructor(e={}){const t={...gm,...e};this.gf=new mo(t.vf,t.Mf),this.bf=new bm(t.mf),this.Sf=t.wf}ku(e){return`${this.gf.ku(e)}${this.Sf}${this.bf.ku(e)}`}}function Cs(s){return 60*s*60*1e3}function Li(s){return 60*s*1e3}const Es=[{xf:(En=1,1e3*En),Cf:10},{xf:Li(1),Cf:20},{xf:Li(5),Cf:21},{xf:Li(30),Cf:22},{xf:Cs(1),Cf:30},{xf:Cs(3),Cf:31},{xf:Cs(6),Cf:32},{xf:Cs(12),Cf:33}];var En;function Tn(s,e){if(s.getUTCFullYear()!==e.getUTCFullYear())return 70;if(s.getUTCMonth()!==e.getUTCMonth())return 60;if(s.getUTCDate()!==e.getUTCDate())return 50;for(let t=Es.length-1;t>=0;--t)if(Math.floor(e.getTime()/Es[t].xf)!==Math.floor(s.getTime()/Es[t].xf))return Es[t].Cf;return 0}function Ai(s){let e=s;if(fs(s)&&(e=Nr(s)),!tr(e))throw new Error("time must be of type BusinessDay");const t=new Date(Date.UTC(e.year,e.month-1,e.day,0,0,0,0));return{yf:Math.round(t.getTime()/1e3),Pf:e}}function Rn(s){if(!uo(s))throw new Error("time must be of type isUTCTimestamp");return{yf:s}}function Nr(s){const e=new Date(s);if(isNaN(e.getTime()))throw new Error(`Invalid date string=${s}, expected format=yyyy-mm-dd`);return{day:e.getUTCDate(),month:e.getUTCMonth()+1,year:e.getUTCFullYear()}}function Pn(s){fs(s.time)&&(s.time=Nr(s.time))}class Ln{options(){return this.yn}setOptions(e){this.yn=e,this.updateFormatter(e.localization)}preprocessData(e){Array.isArray(e)?function(t){t.forEach(Pn)}(e):Pn(e)}createConverterToInternalObj(e){return P(function(t){return t.length===0?null:tr(t[0].time)||fs(t[0].time)?Ai:Rn}(e))}key(e){return typeof e=="object"&&"yf"in e?e.yf:this.key(this.convertHorzItemToInternal(e))}cacheKey(e){const t=e;return t.Pf===void 0?new Date(1e3*t.yf).getTime():new Date(Date.UTC(t.Pf.year,t.Pf.month-1,t.Pf.day)).getTime()}convertHorzItemToInternal(e){return uo(t=e)?Rn(t):tr(t)?Ai(t):Ai(Nr(t));var t}updateFormatter(e){if(!this.yn)return;const t=e.dateFormat;this.yn.timeScale.timeVisible?this.kf=new vm({vf:t,mf:this.yn.timeScale.secondsVisible?"%h:%m:%s":"%h:%m",wf:" ",Mf:e.locale}):this.kf=new mo(t,e.locale)}formatHorzItem(e){const t=e;return this.kf.ku(new Date(1e3*t.yf))}formatTickmark(e,t){const i=function(a,o,l){switch(a){case 0:case 10:return o?l?4:3:2;case 20:case 21:case 22:case 30:case 31:case 32:case 33:return o?3:2;case 50:return 2;case 60:return 1;case 70:return 0}}(e.weight,this.yn.timeScale.timeVisible,this.yn.timeScale.secondsVisible),n=this.yn.timeScale;if(n.tickMarkFormatter!==void 0){const a=n.tickMarkFormatter(e.originalTime,i,t.locale);if(a!==null)return a}return function(a,o,l){const c={};switch(o){case 0:c.year="numeric";break;case 1:c.month="short";break;case 2:c.day="numeric";break;case 3:c.hour12=!1,c.hour="2-digit",c.minute="2-digit";break;case 4:c.hour12=!1,c.hour="2-digit",c.minute="2-digit",c.second="2-digit"}const d=a.Pf===void 0?new Date(1e3*a.yf):new Date(Date.UTC(a.Pf.year,a.Pf.month-1,a.Pf.day));return new Date(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),d.getUTCMilliseconds()).toLocaleString(l,c)}(e.time,i,t.locale)}maxTickMarkWeight(e){let t=e.reduce(mm,e[0]).weight;return t>30&&t<50&&(t=30),t}fillWeightsForPoints(e,t){(function(i,n=0){if(i.length===0)return;let a=n===0?null:i[n-1].time.yf,o=a!==null?new Date(1e3*a):null,l=0;for(let c=n;c1){const c=Math.ceil(l/(i.length-1)),d=new Date(1e3*(i[0].time.yf-c));i[0].timeWeight=Tn(new Date(1e3*i[0].time.yf),d)}})(e,t)}static Tf(e){return Me({localization:{dateFormat:"dd MMM 'yy"}},e??{})}}const At=typeof window<"u";function An(){return!!At&&window.navigator.userAgent.toLowerCase().indexOf("firefox")>-1}function Oi(){return!!At&&/iPhone|iPad|iPod/.test(window.navigator.platform)}function ym(s,e){switch(s){case"custom":return e!==void 0?"custom-object":"series";case"price-line":return"custom-price-line";case"marker":return"series-marker";case"primitive":return"primitive";default:return"series"}}function sr(s){return s+s%2}function wm(s){At&&window.chrome!==void 0&&s.addEventListener("mousedown",e=>{if(e.button===1)return e.preventDefault(),!1})}class fi{constructor(e,t,i){this.Rf=0,this.Df=null,this.If={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY},this.Vf=0,this.Bf=null,this.Ef={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY},this.Af=null,this.Lf=!1,this.zf=null,this.Of=null,this.Nf=!1,this.Ff=!1,this.Wf=!1,this.Hf=null,this.Uf=null,this.$f=null,this.jf=null,this.qf=null,this.Yf=null,this.Kf=null,this.Gf=0,this.Zf=!1,this.Xf=!1,this.Jf=!1,this.Qf=0,this.tp=null,this.ip=!Oi(),this.np=n=>{this.sp(n)},this.ep=n=>{if(this.rp(n)){const a=this.hp(n);if(++this.Vf,this.Bf&&this.Vf>1){const{ap:o}=this.lp(Pe(n),this.Ef);o<30&&!this.Wf&&this.op(a,this.up._p),this.cp()}}else{const a=this.hp(n);if(++this.Rf,this.Df&&this.Rf>1){const{ap:o}=this.lp(Pe(n),this.If);o<5&&!this.Ff&&this.dp(a,this.up.fp),this.pp()}}},this.vp=e,this.up=t,this.yn=i,this.mp()}m(){this.Hf!==null&&(this.Hf(),this.Hf=null),this.Uf!==null&&(this.Uf(),this.Uf=null),this.jf!==null&&(this.jf(),this.jf=null),this.qf!==null&&(this.qf(),this.qf=null),this.Yf!==null&&(this.Yf(),this.Yf=null),this.$f!==null&&(this.$f(),this.$f=null),this.wp(),this.pp()}Mp(e){this.jf&&this.jf();const t=this.gp.bind(this);if(this.jf=()=>{this.vp.removeEventListener("mousemove",t)},this.vp.addEventListener("mousemove",t),this.rp(e))return;const i=this.hp(e);this.dp(i,this.up.bp),this.ip=!0}pp(){this.Df!==null&&clearTimeout(this.Df),this.Rf=0,this.Df=null,this.If={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY}}cp(){this.Bf!==null&&clearTimeout(this.Bf),this.Vf=0,this.Bf=null,this.Ef={_t:Number.NEGATIVE_INFINITY,ut:Number.POSITIVE_INFINITY}}gp(e){if(this.Jf||this.Of!==null||this.rp(e))return;const t=this.hp(e);this.dp(t,this.up.Sp),this.ip=!0}xp(e){const t=zi(e.changedTouches,P(this.tp));if(t===null||(this.Qf=Ts(e),this.Kf!==null)||this.Xf)return;this.Zf=!0;const i=this.lp(Pe(t),P(this.Of)),{Cp:n,yp:a,ap:o}=i;if(this.Nf||!(o<5)){if(!this.Nf){const l=.5*n,c=a>=l&&!this.yn.Pp(),d=l>a&&!this.yn.kp();c||d||(this.Xf=!0),this.Nf=!0,this.Wf=!0,this.wp(),this.cp()}if(!this.Xf){const l=this.hp(e,t);this.op(l,this.up.Tp),gt(e)}}}Rp(e){if(e.button!==0)return;const t=this.lp(Pe(e),P(this.zf)),{ap:i}=t;if(i>=5&&(this.Ff=!0,this.pp()),this.Ff){const n=this.hp(e);this.dp(n,this.up.Dp)}}lp(e,t){const i=Math.abs(t._t-e._t),n=Math.abs(t.ut-e.ut);return{Cp:i,yp:n,ap:i+n}}Ip(e){let t=zi(e.changedTouches,P(this.tp));if(t===null&&e.touches.length===0&&(t=e.changedTouches[0]),t===null)return;this.tp=null,this.Qf=Ts(e),this.wp(),this.Of=null,this.Yf&&(this.Yf(),this.Yf=null);const i=this.hp(e,t);if(this.op(i,this.up.Vp),++this.Vf,this.Bf&&this.Vf>1){const{ap:n}=this.lp(Pe(t),this.Ef);n<30&&!this.Wf&&this.op(i,this.up._p),this.cp()}else this.Wf||(this.op(i,this.up.Bp),this.up.Bp&>(e));this.Vf===0&>(e),e.touches.length===0&&this.Lf&&(this.Lf=!1,gt(e))}sp(e){if(e.button!==0)return;const t=this.hp(e);if(this.zf=null,this.Jf=!1,this.qf&&(this.qf(),this.qf=null),An()&&this.vp.ownerDocument.documentElement.removeEventListener("mouseleave",this.np),!this.rp(e))if(this.dp(t,this.up.Ep),++this.Rf,this.Df&&this.Rf>1){const{ap:i}=this.lp(Pe(e),this.If);i<5&&!this.Ff&&this.dp(t,this.up.fp),this.pp()}else this.Ff||this.dp(t,this.up.Ap)}wp(){this.Af!==null&&(clearTimeout(this.Af),this.Af=null)}Lp(e){if(this.tp!==null)return;const t=e.changedTouches[0];this.tp=t.identifier,this.Qf=Ts(e);const i=this.vp.ownerDocument.documentElement;this.Wf=!1,this.Nf=!1,this.Xf=!1,this.Of=Pe(t),this.Yf&&(this.Yf(),this.Yf=null);{const a=this.xp.bind(this),o=this.Ip.bind(this);this.Yf=()=>{i.removeEventListener("touchmove",a),i.removeEventListener("touchend",o)},i.addEventListener("touchmove",a,{passive:!1}),i.addEventListener("touchend",o,{passive:!1}),this.wp(),this.Af=setTimeout(this.zp.bind(this,e),240)}const n=this.hp(e,t);this.op(n,this.up.Op),this.Bf||(this.Vf=0,this.Bf=setTimeout(this.cp.bind(this),500),this.Ef=Pe(t))}Np(e){if(e.button!==0)return;const t=this.vp.ownerDocument.documentElement;An()&&t.addEventListener("mouseleave",this.np),this.Ff=!1,this.zf=Pe(e),this.qf&&(this.qf(),this.qf=null);{const n=this.Rp.bind(this),a=this.sp.bind(this);this.qf=()=>{t.removeEventListener("mousemove",n),t.removeEventListener("mouseup",a)},t.addEventListener("mousemove",n),t.addEventListener("mouseup",a)}if(this.Jf=!0,this.rp(e))return;const i=this.hp(e);this.dp(i,this.up.Fp),this.Df||(this.Rf=0,this.Df=setTimeout(this.pp.bind(this),500),this.If=Pe(e))}mp(){this.vp.addEventListener("mouseenter",this.Mp.bind(this)),this.vp.addEventListener("touchcancel",this.wp.bind(this));{const e=this.vp.ownerDocument,t=i=>{this.up.Wp&&(i.composed&&this.vp.contains(i.composedPath()[0])||i.target&&this.vp.contains(i.target)||this.up.Wp())};this.Uf=()=>{e.removeEventListener("touchstart",t)},this.Hf=()=>{e.removeEventListener("mousedown",t)},e.addEventListener("mousedown",t),e.addEventListener("touchstart",t,{passive:!0})}Oi()&&(this.$f=()=>{this.vp.removeEventListener("dblclick",this.ep)},this.vp.addEventListener("dblclick",this.ep)),this.vp.addEventListener("mouseleave",this.Hp.bind(this)),this.vp.addEventListener("touchstart",this.Lp.bind(this),{passive:!0}),wm(this.vp),this.vp.addEventListener("mousedown",this.Np.bind(this)),this.Up(),this.vp.addEventListener("touchmove",()=>{},{passive:!1})}Up(){this.up.$p===void 0&&this.up.jp===void 0&&this.up.qp===void 0||(this.vp.addEventListener("touchstart",e=>this.Yp(e.touches),{passive:!0}),this.vp.addEventListener("touchmove",e=>{if(e.touches.length===2&&this.Kf!==null&&this.up.jp!==void 0){const t=On(e.touches[0],e.touches[1])/this.Gf;this.up.jp(this.Kf,t),gt(e)}},{passive:!1}),this.vp.addEventListener("touchend",e=>{this.Yp(e.touches)}))}Yp(e){e.length===1&&(this.Zf=!1),e.length!==2||this.Zf||this.Lf?this.Kp():this.Gp(e)}Gp(e){const t=this.vp.getBoundingClientRect()||{left:0,top:0};this.Kf={_t:(e[0].clientX-t.left+(e[1].clientX-t.left))/2,ut:(e[0].clientY-t.top+(e[1].clientY-t.top))/2},this.Gf=On(e[0],e[1]),this.up.$p!==void 0&&this.up.$p(),this.wp()}Kp(){this.Kf!==null&&(this.Kf=null,this.up.qp!==void 0&&this.up.qp())}Hp(e){if(this.jf&&this.jf(),this.rp(e)||!this.ip)return;const t=this.hp(e);this.dp(t,this.up.Zp),this.ip=!Oi()}zp(e){const t=zi(e.touches,P(this.tp));if(t===null)return;const i=this.hp(e,t);this.op(i,this.up.Xp),this.Wf=!0,this.Lf=!0}rp(e){return e.sourceCapabilities&&e.sourceCapabilities.firesTouchEvents!==void 0?e.sourceCapabilities.firesTouchEvents:Ts(e){e.type!=="touchstart"&>(e)}}}}function On(s,e){const t=s.clientX-e.clientX,i=s.clientY-e.clientY;return Math.sqrt(t*t+i*i)}function gt(s){s.cancelable&&s.preventDefault()}function Pe(s){return{_t:s.pageX,ut:s.pageY}}function Ts(s){return s.timeStamp||performance.now()}function zi(s,e){for(let t=0;t!1,kp:()=>!0}),this.nv={Mv:i,wv:e}}cv(){this.uv.style.background=this.hv.N().layout.panes.separatorColor}gv(e){this.nv!==null&&(this.nv.Mv.style.backgroundColor=this.hv.N().layout.panes.separatorHoverColor)}bv(e){this.nv!==null&&this.rv===null&&(this.nv.Mv.style.backgroundColor="")}Sv(e){if(this.nv===null)return;const t=this.av.yv().F_()+this.ov.yv().F_(),i=t/(this.av.pv().height+this.ov.pv().height),n=30*i;t<=2*n||(this.rv={Pv:e.pageY,kv:this.av.yv().F_(),Tv:t-n,Rv:t,Dv:i,Iv:n},this.nv.wv.style.display="block")}xv(e){const t=this.rv;if(t===null)return;const i=(e.pageY-t.Pv)*t.Dv,n=St(t.kv+i,t.Iv,t.Tv);this.av.yv().W_(n),this.ov.yv().W_(t.Rv-n),this.hv.Qt().ka()}Cv(e){this.rv!==null&&this.nv!==null&&(this.rv=null,this.nv.wv.style.display="none")}}function Ii(s,e){return s.Vv-e.Vv}function $i(s,e,t){const i=(s.Vv-e.Vv)/(s.wt-e.wt);return Math.sign(i)*Math.min(Math.abs(i),t)}class jm{constructor(e,t,i,n){this.Bv=null,this.Ev=null,this.Av=null,this.Lv=null,this.zv=null,this.Ov=0,this.Nv=0,this.Fv=e,this.Wv=t,this.Hv=i,this.Ps=n}Uv(e,t){if(this.Bv!==null){if(this.Bv.wt===t)return void(this.Bv.Vv=e);if(Math.abs(this.Bv.Vv-e)50)return;let i=0;const n=$i(this.Bv,this.Ev,this.Wv),a=Ii(this.Bv,this.Ev),o=[n],l=[a];if(i+=a,this.Av!==null){const d=$i(this.Ev,this.Av,this.Wv);if(Math.sign(d)===Math.sign(n)){const h=Ii(this.Ev,this.Av);if(o.push(d),l.push(h),i+=h,this.Lv!==null){const u=$i(this.Av,this.Lv,this.Wv);if(Math.sign(u)===Math.sign(n)){const m=Ii(this.Av,this.Lv);o.push(u),l.push(m),i+=m}}}}let c=0;for(let d=0;d160?"dark":"light"}Qv(){return this.Gv.N().layout.attributionLogo}im(){const e=new URL(location.href);return e.hostname?"&utm_source="+e.hostname+e.pathname:""}Zv(){this.Jv()&&(this.Xv(),this.vn=this.Qv(),this.vn&&(this.Yv=this.tm(),this.qv=document.createElement("style"),this.qv.innerText="a#tv-attr-logo{--fill:#131722;--stroke:#fff;position:absolute;left:10px;bottom:10px;height:19px;width:35px;margin:0;padding:0;border:0;z-index:3;}a#tv-attr-logo[data-dark]{--fill:#D1D4DC;--stroke:#131722;}",this.jv=document.createElement("a"),this.jv.href=`https://www.tradingview.com/?utm_medium=lwc-link&utm_campaign=lwc-chart${this.im()}`,this.jv.title="Charting by TradingView",this.jv.id="tv-attr-logo",this.jv.target="_blank",this.jv.innerHTML='',this.jv.toggleAttribute("data-dark",this.Yv==="dark"),this.Kv.appendChild(this.qv),this.Kv.appendChild(this.jv)))}}function ut(s,e){const t=P(s.ownerDocument).createElement("canvas");s.appendChild(t);const i=nu(t,{options:{allowResizeObserver:!0},transform:(n,a)=>({width:Math.max(n.width,a.width),height:Math.max(n.height,a.height)})});return i.resizeCanvasElement(e),i}function mt(s){s.width=1,s.height=1,s.getContext("2d")?.clearRect(0,0,1,1)}function $s(s,e,t,i){s.qh&&s.qh(e,t,i)}function Kt(s,e,t,i){s.st(e,t,i)}function ir(s,e,t,i){po(s(t,i),e,i)}function po(s,e,t){for(const i of s){const n=i.Tt(t);n!==null&&e(n)}}function Di(s,e){return t=>function(i){return i.Ft!==void 0}(t)?(t.Ft()?.pl()??"")!==e?[]:t.Qa?.(s)??[]:[]}function zn(s,e,t,i){if(!s.length)return;let n=0;const a=s[0].$t(i,!0);let o=e===1?t/2-(s[0].Hi()-a/2):s[0].Hi()-a/2-t/2;o=Math.max(0,o);for(let l=1;lm-h:ut)&&o>0){const f=e===1?-1-b:b-t,v=Math.min(f,o);for(let p=n;p{this.lm||this.yt._m().Qt().mr()},this.um=()=>{this.lm||this.yt._m().Qt().mr()},this.yt=e,this.yn=t,this.Ro=t.layout,this.bd=i,this.dm=n==="left",this.fm=Di("normal",n),this.pm=Di("top",n),this.vm=Di("bottom",n),this.uv=document.createElement("div"),this.uv.style.height="100%",this.uv.style.overflow="hidden",this.uv.style.width="25px",this.uv.style.left="0",this.uv.style.position="relative",this.wm=ut(this.uv,re({width:16,height:16})),this.wm.subscribeSuggestedBitmapSizeChanged(this.om);const a=this.wm.canvasElement;a.style.position="absolute",a.style.zIndex="1",a.style.left="0",a.style.top="0",this.Mm=ut(this.uv,re({width:16,height:16})),this.Mm.subscribeSuggestedBitmapSizeChanged(this.um);const o=this.Mm.canvasElement;o.style.position="absolute",o.style.zIndex="2",o.style.left="0",o.style.top="0";const l={Fp:this.Sv.bind(this),Op:this.Sv.bind(this),Dp:this.xv.bind(this),Tp:this.xv.bind(this),Wp:this.gm.bind(this),Ep:this.Cv.bind(this),Vp:this.Cv.bind(this),fp:this.bm.bind(this),_p:this.bm.bind(this),bp:this.Sm.bind(this),Zp:this.bv.bind(this)};this.sv=new fi(this.Mm.canvasElement,l,{Pp:()=>!this.yn.handleScroll.vertTouchDrag,kp:()=>!0})}m(){this.sv.m(),this.Mm.unsubscribeSuggestedBitmapSizeChanged(this.um),mt(this.Mm.canvasElement),this.Mm.dispose(),this.wm.unsubscribeSuggestedBitmapSizeChanged(this.om),mt(this.wm.canvasElement),this.wm.dispose(),this.Ki!==null&&this.Ki.__().u(this),this.Ki=null}fv(){return this.uv}P(){return this.Ro.fontSize}xm(){const e=this.bd.N();return this.hm!==e.k&&(this.rm.Os(),this.hm=e.k),e}Cm(){if(this.Ki===null)return 0;let e=0;const t=this.xm(),i=P(this.wm.canvasElement.getContext("2d",{colorSpace:this.yt._m().N().layout.colorSpace}));i.save();const n=this.Ki.zl();i.font=this.ym(),n.length>0&&(e=Math.max(this.rm.Ii(i,n[0].eo),this.rm.Ii(i,n[n.length-1].eo)));const a=this.Pm();for(let d=a.length;d--;){const h=this.rm.Ii(i,a[d].ri());h>e&&(e=h)}const o=this.Ki.Lt();if(o!==null&&this.nm!==null&&(l=this.yn.crosshair).mode!==2&&l.horzLine.visible&&l.horzLine.labelVisible){const d=this.Ki.Tn(1,o),h=this.Ki.Tn(this.nm.height-2,o);e=Math.max(e,this.rm.Ii(i,this.Ki.Ji(Math.floor(Math.min(d,h))+.11111111111111,o)),this.rm.Ii(i,this.Ki.Ji(Math.ceil(Math.max(d,h))-.11111111111111,o)))}var l;i.restore();const c=e||34;return sr(Math.ceil(t.S+t.C+t.V+t.B+5+c))}km(e){this.nm!==null&&it(this.nm,e)||(this.nm=e,this.lm=!0,this.wm.resizeCanvasElement(e),this.Mm.resizeCanvasElement(e),this.lm=!1,this.uv.style.width=`${e.width}px`,this.uv.style.height=`${e.height}px`)}Tm(){return P(this.nm).width}un(e){this.Ki!==e&&(this.Ki!==null&&this.Ki.__().u(this),this.Ki=e,e.__().i(this.wo.bind(this),this))}Ft(){return this.Ki}Os(){const e=this.yt.yv();this.yt._m().Qt().au(e,P(this.Ft()))}Rm(e){if(this.nm===null)return;const t={colorSpace:this.yt._m().N().layout.colorSpace};if(e!==1){this.Dm(),this.wm.applySuggestedBitmapSize();const n=dt(this.wm,t);n!==null&&(n.useBitmapCoordinateSpace(a=>{this.Im(a),this.Vm(a)}),this.yt.Bm(n,this.vm),this.Em(n),this.yt.Bm(n,this.fm),this.Am(n))}this.Mm.applySuggestedBitmapSize();const i=dt(this.Mm,t);i!==null&&(i.useBitmapCoordinateSpace(({context:n,bitmapSize:a})=>{n.clearRect(0,0,a.width,a.height)}),this.Lm(i),this.yt.Bm(i,this.pm))}vv(){return this.wm.bitmapSize}mv(e,t,i,n){const a=this.vv();if(a.width>0&&a.height>0&&(e.drawImage(this.wm.canvasElement,t,i),n)){const o=this.Mm.canvasElement;e.drawImage(o,t,i)}}Pt(){this.Ki?.zl()}Sv(e){if(this.Ki===null||this.Ki.Zi()||!this.yn.handleScale.axisPressedMouseMove.price)return;const t=this.yt._m().Qt(),i=this.yt.yv();this.sm=!0,t.Q_(i,this.Ki,e.localY)}xv(e){if(this.Ki===null||!this.yn.handleScale.axisPressedMouseMove.price)return;const t=this.yt._m().Qt(),i=this.yt.yv(),n=this.Ki;t.tu(i,n,e.localY)}gm(){if(this.Ki===null||!this.yn.handleScale.axisPressedMouseMove.price)return;const e=this.yt._m().Qt(),t=this.yt.yv(),i=this.Ki;this.sm&&(this.sm=!1,e.iu(t,i))}Cv(e){if(this.Ki===null||!this.yn.handleScale.axisPressedMouseMove.price)return;const t=this.yt._m().Qt(),i=this.yt.yv();this.sm=!1,t.iu(i,this.Ki)}bm(e){this.yn.handleScale.axisDoubleClickReset.price&&this.Os()}Sm(e){this.Ki!==null&&(!this.yt._m().Qt().N().handleScale.axisPressedMouseMove.price||this.Ki.je()||this.Ki.No()||this.zm(1))}bv(e){this.zm(0)}Pm(){const e=[],t=this.Ki===null?void 0:this.Ki;return(i=>{for(let n=0;n{o.fillStyle=i.borderColor;const d=Math.max(1,Math.floor(c)),h=Math.floor(.5*c),u=Math.round(n.C*l);o.beginPath();for(const m of t)o.rect(Math.floor(a*l),Math.round(m.Vl*c)-h,u,d);o.fill()}),e.useMediaCoordinateSpace(({context:o})=>{o.font=this.ym(),o.fillStyle=i.textColor??this.Ro.textColor,o.textAlign=this.dm?"right":"left",o.textBaseline="middle";const l=this.dm?Math.round(a-n.V):Math.round(a+n.C+n.V),c=t.map(d=>this.rm.Di(o,d.eo));for(let d=t.length;d--;){const h=t[d];o.fillText(h.eo,l,h.Vl+c[d])}})}Dm(){if(this.nm===null||this.Ki===null)return;let e=this.nm.height/2;const t=[],i=this.Ki.Dt().slice(),n=this.yt.yv(),a=this.xm();this.Ki===n.Zs()&&this.yt.yv().Dt().forEach(c=>{n.Gs(c)&&i.push(c)});const o=this.Ki.kl()[0],l=this.Ki;i.forEach(c=>{const d=c.qn(n,l);d.forEach(h=>{h.$i()&&h.Wi()===null&&(h.Ui(null),t.push(h))}),o===c&&d.length>0&&(e=d[0].Ei())}),this.Ki.N().alignLabels&&this.Om(t,a,e)}Om(e,t,i){if(this.nm===null)return;const n=e.filter(o=>o.Ei()<=i),a=e.filter(o=>o.Ei()>i);n.sort((o,l)=>l.Ei()-o.Ei()),n.length&&a.length&&a.push(n[0]),a.sort((o,l)=>o.Ei()-l.Ei());for(const o of e){const l=Math.floor(o.$t(t)/2),c=o.Ei();c>-l&&cthis.nm.height-l&&c{a.ji()&&a.Tt(P(this.Ki)).st(e,i,this.rm,n)})}Lm(e){if(this.nm===null||this.Ki===null)return;const t=this.yt._m().Qt(),i=[],n=this.yt.yv(),a=t.Vd().qn(n,this.Ki);a.length&&i.push(a);const o=this.xm(),l=this.dm?"right":"left";i.forEach(c=>{c.forEach(d=>{d.Tt(P(this.Ki)).st(e,o,this.rm,l)})})}zm(e){this.uv.style.cursor=e===1?"ns-resize":"default"}wo(){const e=this.Cm();this.am{this.lm||this.Jm===null||this.sn().mr()},this.um=()=>{this.lm||this.Jm===null||this.sn().mr()},this.Gv=e,this.Jm=t,this.Jm.mu().i(this.Qm.bind(this),this,!0),this.tw=document.createElement("td"),this.tw.style.padding="0",this.tw.style.position="relative";const i=document.createElement("div");i.style.width="100%",i.style.height="100%",i.style.position="relative",i.style.overflow="hidden",this.iw=document.createElement("td"),this.iw.style.padding="0",this.nw=document.createElement("td"),this.nw.style.padding="0",this.tw.appendChild(i),this.wm=ut(i,re({width:16,height:16})),this.wm.subscribeSuggestedBitmapSizeChanged(this.om);const n=this.wm.canvasElement;n.style.position="absolute",n.style.zIndex="1",n.style.left="0",n.style.top="0",this.Mm=ut(i,re({width:16,height:16})),this.Mm.subscribeSuggestedBitmapSizeChanged(this.um);const a=this.Mm.canvasElement;a.style.position="absolute",a.style.zIndex="2",a.style.left="0",a.style.top="0",this._v=document.createElement("tr"),this._v.appendChild(this.iw),this._v.appendChild(this.tw),this._v.appendChild(this.nw),this.sw(),this.sv=new fi(this.Mm.canvasElement,this,{Pp:()=>this.Km===null&&!this.Gv.N().handleScroll.vertTouchDrag,kp:()=>this.Km===null&&!this.Gv.N().handleScroll.horzTouchDrag})}m(){this.Nm!==null&&this.Nm.m(),this.Fm!==null&&this.Fm.m(),this.Wm=null,this.Mm.unsubscribeSuggestedBitmapSizeChanged(this.um),mt(this.Mm.canvasElement),this.Mm.dispose(),this.wm.unsubscribeSuggestedBitmapSizeChanged(this.om),mt(this.wm.canvasElement),this.wm.dispose(),this.Jm!==null&&(this.Jm.mu().u(this),this.Jm.m()),this.sv.m()}yv(){return P(this.Jm)}ew(e){this.Jm!==null&&this.Jm.mu().u(this),this.Jm=e,this.Jm!==null&&this.Jm.mu().i(jr.prototype.Qm.bind(this),this,!0),this.sw(),this.Gv.lv().indexOf(this)===this.Gv.lv().length-1?(this.Wm=this.Wm??new _m(this.tw,this.Gv),this.Wm.Pt()):(this.Wm?.Xv(),this.Wm=null)}_m(){return this.Gv}fv(){return this._v}sw(){if(this.Jm!==null&&(this.rw(),this.sn().Jn().length!==0)){if(this.Nm!==null){const e=this.Jm.X_();this.Nm.un(P(e))}if(this.Fm!==null){const e=this.Jm.J_();this.Fm.un(P(e))}}}hw(){this.Nm!==null&&this.Nm.Pt(),this.Fm!==null&&this.Fm.Pt()}F_(){return this.Jm!==null?this.Jm.F_():0}W_(e){this.Jm&&this.Jm.W_(e)}bp(e){if(!this.Jm)return;this.aw();const t=e.localX,i=e.localY;this.lw(t,i,e)}Fp(e){this.aw(),this.ow(),this.lw(e.localX,e.localY,e)}Sp(e){if(!this.Jm)return;this.aw();const t=e.localX,i=e.localY;this.lw(t,i,e)}Ap(e){this.Jm!==null&&(this.aw(),this.lw(e.localX,e.localY,e),this._w(e))}fp(e){this.Jm!==null&&this.uw(this.jm,e)}_p(e){this.fp(e)}Dp(e){this.aw(),this.cw(e),this.lw(e.localX,e.localY,e)}Ep(e){this.Jm!==null&&(this.aw(),this.Ym=!1,this.dw(e))}Bp(e){this.Jm!==null&&this._w(e)}Xp(e){if(this.Ym=!0,this.Km===null){const t={x:e.localX,y:e.localY};this.fw(t,t,e)}}Zp(e){this.Jm!==null&&(this.aw(),this.Jm.Qt().Rd(null),this.pw())}mw(){return this.$m}ww(){return this.jm}$p(){this.qm=1,this.sn().cs()}jp(e,t){if(!this.Gv.N().handleScale.pinch)return;const i=5*(t-this.qm);this.qm=t,this.sn().Wd(e._t,i)}Op(e){this.Ym=!1,this.Gm=this.Km!==null,this.ow();const t=this.sn().Vd();this.Km!==null&&t.It()&&(this.Zm={x:t.ni(),y:t.si()},this.Km={x:e.localX,y:e.localY})}Tp(e){if(this.Jm===null)return;const t=e.localX,i=e.localY;if(this.Km===null)this.cw(e);else{this.Gm=!1;const n=P(this.Zm),a=n.x+(t-this.Km.x),o=n.y+(i-this.Km.y);this.lw(a,o,e)}}Vp(e){this._m().N().trackingMode.exitMode===0&&(this.Gm=!0),this.Mw(),this.dw(e)}Qs(e,t){const i=this.Jm;return i===null?null:co(i,e,t)}gw(e,t){P(t==="left"?this.Nm:this.Fm).km(re({width:e,height:this.nm.height}))}pv(){return this.nm}km(e){it(this.nm,e)||(this.nm=e,this.lm=!0,this.wm.resizeCanvasElement(e),this.Mm.resizeCanvasElement(e),this.lm=!1,this.tw.style.width=e.width+"px",this.tw.style.height=e.height+"px")}bw(){const e=P(this.Jm);e.G_(e.X_()),e.G_(e.J_());for(const t of e.kl())if(e.Gs(t)){const i=t.Ft();i!==null&&e.G_(i),t.Nn()}for(const t of e.Mu())t.Nn()}vv(){return this.wm.bitmapSize}mv(e,t,i,n){const a=this.vv();if(a.width>0&&a.height>0&&(e.drawImage(this.wm.canvasElement,t,i),n)){const o=this.Mm.canvasElement;e!==null&&e.drawImage(o,t,i)}}Rm(e){if(e===0||this.Jm===null)return;e>1&&this.bw(),this.Nm!==null&&this.Nm.Rm(e),this.Fm!==null&&this.Fm.Rm(e);const t={colorSpace:this.Gv.N().layout.colorSpace};if(e!==1){this.wm.applySuggestedBitmapSize();const n=dt(this.wm,t);n!==null&&(n.useBitmapCoordinateSpace(a=>{this.Im(a)}),this.Jm&&(this.Sw(n,Sm),this.xw(n),this.Sw(n,Bi),this.Sw(n,$n)))}this.Mm.applySuggestedBitmapSize();const i=dt(this.Mm,t);i!==null&&(i.useBitmapCoordinateSpace(({context:n,bitmapSize:a})=>{n.clearRect(0,0,a.width,a.height)}),this.Cw(i),this.Sw(i,km),this.Sw(i,$n))}yw(){return this.Nm}Pw(){return this.Fm}Bm(e,t){this.Sw(e,t)}Qm(){this.Jm!==null&&this.Jm.mu().u(this),this.Jm=null}_w(e){this.uw(this.$m,e)}uw(e,t){const i=t.localX,n=t.localY;e.v()&&e.p(this.sn().Et().Vc(i),{x:i,y:n},t)}Im({context:e,bitmapSize:t}){const{width:i,height:n}=t,a=this.sn(),o=a.$(),l=a.af();o===l?di(e,0,0,i,n,l):Xa(e,0,0,i,n,o,l)}xw(e){const t=P(this.Jm),i=t.wu().wr().Tt(t);i!==null&&i.st(e,!1)}Cw(e){this.kw(e,Bi,Kt,this.sn().Vd())}Sw(e,t){const i=P(this.Jm),n=t===Bi?this.Tw():null,a=n===null?null:this.Rw(n,i),o=i.Mu();if(a===null||n===null){const d=i._u();return this.Dw(e,t,$s,o,d),void this.Dw(e,t,Kt,o,d)}const l=i.Dt(),c=d=>d===n?a.Za:void 0;this.Dw(e,t,$s,o,l,c),this.Dw(e,t,Kt,o,l,c),this.kw(e,t,$s,n,a.qa),this.kw(e,t,Kt,n,a.qa)}Dw(e,t,i,n,a,o){for(const l of n)this.kw(e,t,i,l);if(o!==void 0)for(const l of a)this.kw(e,t,i,l,o(l));else for(const l of a)this.kw(e,t,i,l)}Tw(){const e=P(this.Jm),t=e.Qt().cu()?.uu;if(!e.Qt().N().hoveredSeriesOnTop||t===void 0)return null;for(const i of e.Dt())if(i===t)return i;return null}Rw(e,t){const i=e.Ga?.(t)??null;return i===null||i.qa.length===0?null:i}kw(e,t,i,n,a){const o=P(this.Jm),l=o.Qt().cu(),c=l!==null&&l.uu===n,d=l!==null&&c&&l.bu!==void 0?l.bu.ie:void 0,h=u=>i(u,e,c,d);a===void 0?ir(t,h,n,o):po(a,h,o)}rw(){if(this.Jm===null)return;const e=this.Gv,t=this.Jm.X_().N().visible,i=this.Jm.J_().N().visible;t||this.Nm===null||(this.iw.removeChild(this.Nm.fv()),this.Nm.m(),this.Nm=null),i||this.Fm===null||(this.nw.removeChild(this.Fm.fv()),this.Fm.m(),this.Fm=null);const n=e.Qt().Jd();t&&this.Nm===null&&(this.Nm=new In(this,e.N(),n,"left"),this.iw.appendChild(this.Nm.fv())),i&&this.Fm===null&&(this.Fm=new In(this,e.N(),n,"right"),this.nw.appendChild(this.Fm.fv()))}Iw(e){return e.Jp&&this.Ym||this.Km!==null}lw(e,t,i){e=Math.max(0,Math.min(e,this.nm.width-1)),t=Math.max(0,Math.min(t,this.nm.height-1)),this.sn().Kd(e,t,i,P(this.Jm))}pw(){this.sn().Zd()}Mw(){this.Gm&&(this.Km=null,this.pw())}fw(e,t,i){this.Km=e,this.Gm=!1,this.lw(t.x,t.y,i);const n=this.sn().Vd();this.Zm={x:n.ni(),y:n.si()}}sn(){return this.Gv.Qt()}dw(e){if(!this.Um)return;const t=this.sn(),i=this.yv();if(t.eu(i,i.kn()),this.Hm=null,this.Um=!1,t.jd(),this.Xm!==null){const n=performance.now(),a=t.Et();this.Xm.me(a.Oc(),n),this.Xm.Kc(n)||t.ps(this.Xm)}}aw(){this.Km=null}ow(){if(this.Jm){if(this.sn().cs(),document.activeElement!==document.body&&document.activeElement!==document.documentElement)P(document.activeElement).blur();else{const e=document.getSelection();e!==null&&e.removeAllRanges()}!this.Jm.kn().Zi()&&this.sn().Et().Zi()}}cw(e){if(this.Jm===null)return;const t=this.sn(),i=t.Et();if(i.Zi())return;const n=this.Gv.N(),a=n.handleScroll,o=n.kineticScroll;if((!a.pressedMouseMove||e.Jp)&&(!a.horzTouchDrag&&!a.vertTouchDrag||!e.Jp))return;const l=this.Jm.kn(),c=performance.now();if(this.Hm!==null||this.Iw(e)||(this.Hm={x:e.clientX,y:e.clientY,yf:c,Vw:e.localX,Bw:e.localY}),this.Hm!==null&&!this.Um&&(this.Hm.x!==e.clientX||this.Hm.y!==e.clientY)){if(e.Jp&&o.touch||!e.Jp&&o.mouse){const d=i.ml();this.Xm=new jm(.2/d,7/d,.997,15/d),this.Xm.Uv(i.Oc(),this.Hm.yf)}else this.Xm=null;l.Zi()||t.nu(this.Jm,l,e.localY),t.Ud(e.localX),this.Um=!0}this.Um&&(l.Zi()||t.su(this.Jm,l,e.localY),t.$d(e.localX),this.Xm!==null&&this.Xm.Uv(i.Oc(),c))}}class Dn{constructor(e,t,i,n,a){this.xt=!0,this.nm=re({width:0,height:0}),this.om=()=>this.Rm(3),this.dm=e==="left",this.bd=i.Jd,this.yn=t,this.Ew=n,this.Aw=a,this.uv=document.createElement("div"),this.uv.style.width="25px",this.uv.style.height="100%",this.uv.style.overflow="hidden",this.wm=ut(this.uv,re({width:16,height:16})),this.wm.subscribeSuggestedBitmapSizeChanged(this.om)}m(){this.wm.unsubscribeSuggestedBitmapSizeChanged(this.om),mt(this.wm.canvasElement),this.wm.dispose()}fv(){return this.uv}pv(){return this.nm}km(e){it(this.nm,e)||(this.nm=e,this.wm.resizeCanvasElement(e),this.uv.style.width=`${e.width}px`,this.uv.style.height=`${e.height}px`,this.xt=!0)}Rm(e){if(e<3&&!this.xt||this.nm.width===0||this.nm.height===0)return;this.xt=!1,this.wm.applySuggestedBitmapSize();const t=dt(this.wm,{colorSpace:this.yn.layout.colorSpace});t!==null&&t.useBitmapCoordinateSpace(i=>{this.Im(i),this.Vm(i)})}vv(){return this.wm.bitmapSize}mv(e,t,i){const n=this.vv();n.width>0&&n.height>0&&e.drawImage(this.wm.canvasElement,t,i)}Vm({context:e,bitmapSize:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(!this.Ew())return;e.fillStyle=this.yn.timeScale.borderColor;const a=Math.floor(this.bd.N().S*i),o=Math.floor(this.bd.N().S*n),l=this.dm?t.width-a:0;e.fillRect(l,0,a,o)}Im({context:e,bitmapSize:t}){di(e,0,0,t.width,t.height,this.Aw())}}function _r(s){return e=>e.tl?.(s)??[]}const Mm=_r("normal"),Cm=_r("top"),Em=_r("bottom");class Tm{constructor(e,t){this.Lw=null,this.zw=null,this.M=null,this.Ow=!1,this.nm=re({width:0,height:0}),this.Nw=new le,this.rm=new Gs(5),this.lm=!1,this.om=()=>{this.lm||this.Gv.Qt().mr()},this.um=()=>{this.lm||this.Gv.Qt().mr()},this.Gv=e,this.Pu=t,this.yn=e.N().layout,this.jv=document.createElement("tr"),this.Fw=document.createElement("td"),this.Fw.style.padding="0",this.Ww=document.createElement("td"),this.Ww.style.padding="0",this.uv=document.createElement("td"),this.uv.style.height="25px",this.uv.style.padding="0",this.Hw=document.createElement("div"),this.Hw.style.width="100%",this.Hw.style.height="100%",this.Hw.style.position="relative",this.Hw.style.overflow="hidden",this.uv.appendChild(this.Hw),this.wm=ut(this.Hw,re({width:16,height:16})),this.wm.subscribeSuggestedBitmapSizeChanged(this.om);const i=this.wm.canvasElement;i.style.position="absolute",i.style.zIndex="1",i.style.left="0",i.style.top="0",this.Mm=ut(this.Hw,re({width:16,height:16})),this.Mm.subscribeSuggestedBitmapSizeChanged(this.um);const n=this.Mm.canvasElement;n.style.position="absolute",n.style.zIndex="2",n.style.left="0",n.style.top="0",this.jv.appendChild(this.Fw),this.jv.appendChild(this.uv),this.jv.appendChild(this.Ww),this.Uw(),this.Gv.Qt().N_().i(this.Uw.bind(this),this),this.sv=new fi(this.Mm.canvasElement,this,{Pp:()=>!0,kp:()=>!this.Gv.N().handleScroll.horzTouchDrag})}m(){this.sv.m(),this.Lw!==null&&this.Lw.m(),this.zw!==null&&this.zw.m(),this.Mm.unsubscribeSuggestedBitmapSizeChanged(this.um),mt(this.Mm.canvasElement),this.Mm.dispose(),this.wm.unsubscribeSuggestedBitmapSizeChanged(this.om),mt(this.wm.canvasElement),this.wm.dispose()}fv(){return this.jv}$w(){return this.Lw}jw(){return this.zw}Fp(e){if(this.Ow)return;this.Ow=!0;const t=this.Gv.Qt();!t.Et().Zi()&&this.Gv.N().handleScale.axisPressedMouseMove.time&&t.Fd(e.localX)}Op(e){this.Fp(e)}Wp(){const e=this.Gv.Qt();!e.Et().Zi()&&this.Ow&&(this.Ow=!1,this.Gv.N().handleScale.axisPressedMouseMove.time&&e.Yd())}Dp(e){const t=this.Gv.Qt();!t.Et().Zi()&&this.Gv.N().handleScale.axisPressedMouseMove.time&&t.qd(e.localX)}Tp(e){this.Dp(e)}Ep(){this.Ow=!1;const e=this.Gv.Qt();e.Et().Zi()&&!this.Gv.N().handleScale.axisPressedMouseMove.time||e.Yd()}Vp(){this.Ep()}fp(){this.Gv.N().handleScale.axisDoubleClickReset.time&&this.Gv.Qt().ws()}_p(){this.fp()}bp(){this.Gv.Qt().N().handleScale.axisPressedMouseMove.time&&this.zm(1)}Zp(){this.zm(0)}pv(){return this.nm}qw(){return this.Nw}Yw(e,t,i){it(this.nm,e)||(this.nm=e,this.lm=!0,this.wm.resizeCanvasElement(e),this.Mm.resizeCanvasElement(e),this.lm=!1,this.uv.style.width=`${e.width}px`,this.uv.style.height=`${e.height}px`,this.Nw.p(e)),this.Lw!==null&&this.Lw.km(re({width:t,height:e.height})),this.zw!==null&&this.zw.km(re({width:i,height:e.height}))}Kw(){const e=this.Gw();return Math.ceil(e.S+e.C+e.P+e.A+e.I+e.Zw)}Pt(){this.Gv.Qt().Et().zl()}vv(){return this.wm.bitmapSize}mv(e,t,i,n){const a=this.vv();if(a.width>0&&a.height>0&&(e.drawImage(this.wm.canvasElement,t,i),n)){const o=this.Mm.canvasElement;e.drawImage(o,t,i)}}Rm(e){if(e===0)return;const t={colorSpace:this.yn.colorSpace};if(e!==1){this.wm.applySuggestedBitmapSize();const n=dt(this.wm,t);n!==null&&(n.useBitmapCoordinateSpace(a=>{this.Im(a),this.Vm(a),this.Xw(n,Em)}),this.Em(n),this.Xw(n,Mm)),this.Lw!==null&&this.Lw.Rm(e),this.zw!==null&&this.zw.Rm(e)}this.Mm.applySuggestedBitmapSize();const i=dt(this.Mm,t);i!==null&&(i.useBitmapCoordinateSpace(({context:n,bitmapSize:a})=>{n.clearRect(0,0,a.width,a.height)}),this.Jw([...this.Gv.Qt().Jn(),this.Gv.Qt().Vd()],i),this.Xw(i,Cm))}Xw(e,t){const i=this.Gv.Qt().Jn();for(const n of i)ir(t,a=>$s(a,e,!1,void 0),n,void 0);for(const n of i)ir(t,a=>Kt(a,e,!1,void 0),n,void 0)}Im({context:e,bitmapSize:t}){di(e,0,0,t.width,t.height,this.Gv.Qt().af())}Vm({context:e,bitmapSize:t,verticalPixelRatio:i}){if(this.Gv.N().timeScale.borderVisible){e.fillStyle=this.Qw();const n=Math.max(1,Math.floor(this.Gw().S*i));e.fillRect(0,0,t.width,n)}}Em(e){const t=this.Gv.Qt().Et(),i=t.zl();if(!i||i.length===0)return;const n=this.Pu.maxTickMarkWeight(i),a=this.Gw(),o=t.N();o.borderVisible&&o.ticksVisible&&e.useBitmapCoordinateSpace(({context:l,horizontalPixelRatio:c,verticalPixelRatio:d})=>{l.strokeStyle=this.Qw(),l.fillStyle=this.Qw();const h=Math.max(1,Math.floor(c)),u=Math.floor(.5*c);l.beginPath();const m=Math.round(a.C*d);for(let x=i.length;x--;){const b=Math.round(i[x].coord*c);l.rect(b-u,0,h,m)}l.fill()}),e.useMediaCoordinateSpace(({context:l})=>{const c=a.S+a.C+a.A+a.P/2;l.textAlign="center",l.textBaseline="middle",l.fillStyle=this.H(),l.font=this.ym();for(const d of i)if(d.weight=n){const h=d.needAlignCoordinate?this.tM(l,d.coord,d.label):d.coord;l.fillText(d.label,h,c)}})}tM(e,t,i){const n=this.rm.Ii(e,i),a=n/2,o=Math.floor(t-a)+.5;return o<0?t+=Math.abs(0-o):o+n>this.nm.width&&(t-=Math.abs(this.nm.width-(o+n))),t}Jw(e,t){const i=this.Gw();for(const n of e)for(const a of n.dn())a.Tt().st(t,i)}Qw(){return this.Gv.N().timeScale.borderColor}H(){return this.yn.textColor}F(){return this.yn.fontSize}ym(){return Ks(this.F(),this.yn.fontFamily)}iM(){return Ks(this.F(),this.yn.fontFamily,"bold")}Gw(){this.M===null&&(this.M={S:1,L:NaN,A:NaN,I:NaN,tn:NaN,C:5,P:NaN,k:"",Qi:new Gs,Zw:0});const e=this.M,t=this.ym();if(e.k!==t){const i=this.F();e.P=i,e.k=t,e.A=3*i/12,e.I=3*i/12,e.tn=9*i/12,e.L=0,e.Zw=4*i/12,e.Qi.Os()}return this.M}zm(e){this.uv.style.cursor=e===1?"ew-resize":"default"}Uw(){const e=this.Gv.Qt(),t=e.N();t.leftPriceScale.visible||this.Lw===null||(this.Fw.removeChild(this.Lw.fv()),this.Lw.m(),this.Lw=null),t.rightPriceScale.visible||this.zw===null||(this.Ww.removeChild(this.zw.fv()),this.zw.m(),this.zw=null);const i={Jd:this.Gv.Qt().Jd()},n=()=>t.leftPriceScale.borderVisible&&e.Et().N().borderVisible,a=()=>e.af();t.leftPriceScale.visible&&this.Lw===null&&(this.Lw=new Dn("left",t,i,n,a),this.Fw.appendChild(this.Lw.fv())),t.rightPriceScale.visible&&this.zw===null&&(this.zw=new Dn("right",t,i,n,a),this.Ww.appendChild(this.zw.fv()))}}const Rm=!!At&&!!navigator.userAgentData&&navigator.userAgentData.brands.some(s=>s.brand.includes("Chromium"))&&!!At&&(navigator?.userAgentData?.platform?navigator.userAgentData.platform==="Windows":navigator.userAgent.toLowerCase().indexOf("win")>=0);class Pm{constructor(e,t,i){var n;this.nM=[],this.sM=[],this.eM=0,this.oo=0,this.k_=0,this.rM=0,this.hM=0,this.aM=null,this.lM=!1,this.$m=new le,this.jm=new le,this.wd=new le,this.oM=null,this._M=null,this.Kv=e,this.yn=t,this.Pu=i,this.jv=document.createElement("div"),this.jv.classList.add("tv-lightweight-charts"),this.jv.style.overflow="hidden",this.jv.style.direction="ltr",this.jv.style.width="100%",this.jv.style.height="100%",(n=this.jv).style.userSelect="none",n.style.webkitUserSelect="none",n.style.msUserSelect="none",n.style.MozUserSelect="none",n.style.webkitTapHighlightColor="transparent",this.uM=document.createElement("table"),this.uM.setAttribute("cellspacing","0"),this.jv.appendChild(this.uM),this.cM=this.dM.bind(this),Fi(this.yn)&&this.fM(!0),this.sn=new fm(this.gd.bind(this),this.yn,i),this.Qt().Bd().i(this.pM.bind(this),this),this.vM=new Tm(this,this.Pu),this.uM.appendChild(this.vM.fv());const a=t.autoSize&&this.mM();let o=this.yn.width,l=this.yn.height;if(a||o===0||l===0){const c=e.getBoundingClientRect();o=o||c.width,l=l||c.height}this.wM(o,l),this.MM(),e.appendChild(this.jv),this.gM(),this.sn.Et().Jc().i(this.sn.ka.bind(this.sn),this),this.sn.N_().i(this.sn.ka.bind(this.sn),this)}Qt(){return this.sn}N(){return this.yn}lv(){return this.nM}bM(){return this.vM}m(){this.fM(!1),this.eM!==0&&window.cancelAnimationFrame(this.eM),this.sn.Bd().u(this),this.sn.Et().Jc().u(this),this.sn.N_().u(this),this.sn.m();for(const e of this.nM)this.uM.removeChild(e.fv()),e.mw().u(this),e.ww().u(this),e.m();this.nM=[];for(const e of this.sM)this.SM(e);this.sM=[],P(this.vM).m(),this.jv.parentElement!==null&&this.jv.parentElement.removeChild(this.jv),this.wd.m(),this.$m.m(),this.jm.m(),this.xM()}wM(e,t,i=!1){if(this.oo===t&&this.k_===e)return;const n=function(l){const c=Math.floor(l.width),d=Math.floor(l.height);return re({width:c-c%2,height:d-d%2})}(re({width:e,height:t}));this.oo=n.height,this.k_=n.width;const a=this.oo+"px",o=this.k_+"px";if(this.CM()||(P(this.jv).style.height=a,P(this.jv).style.width=o),this.uM.style.height=a,this.uM.style.width=o,i){this.eM!==0&&(window.cancelAnimationFrame(this.eM),this.eM=0),this.lM=!1;const l=ue.ys();this.aM!==null&&(l.Ss(this.aM),this.aM=null),this.yM(l,performance.now())}else this.sn.ka()}Rm(e){e===void 0&&(e=ue.ys());for(let t=0;t{e.Pt()})}kM(e){(e.autoSize!==void 0||!this.oM||e.width===void 0&&e.height===void 0)&&(e.autoSize&&!this.oM&&this.mM(),e.autoSize===!1&&this.oM!==null&&this.xM(),e.autoSize||e.width===void 0&&e.height===void 0||this.wM(e.width||this.k_,e.height||this.oo))}RM(e,t){let i=0,n=0;const a=this.nM[0],o=(c,d)=>{let h=0;for(let u=0;u{P(c==="left"?this.vM.$w():this.vM.jw()).mv(P(e),d,h)};if(this.yn.timeScale.visible){const c=this.vM.vv();if(e!==null){let d=0;this.IM()&&(l("left",d,n),d=P(a.yw()).vv().width),this.vM.mv(e,d,n,t),d+=c.width,this.VM()&&l("right",d,n)}n+=c.height}return re({width:i,height:n})}LM(){let e=0,t=0,i=0;for(const v of this.nM)this.IM()&&(t=Math.max(t,P(v.yw()).Cm(),this.yn.leftPriceScale.minimumWidth)),this.VM()&&(i=Math.max(i,P(v.Pw()).Cm(),this.yn.rightPriceScale.minimumWidth)),e+=v.F_();t=sr(t),i=sr(i);const n=this.k_,a=this.oo,o=Math.max(n-t-i,0),l=1*this.sM.length,c=this.yn.timeScale.visible;let d=c?Math.max(this.vM.Kw(),this.yn.timeScale.minimumHeight):0;var h;d=(h=d)+h%2;const u=l+d,m=a{n.hw()}),this.aM?.ls()===3&&(this.aM.Ss(e),this.OM(),this.NM(this.aM),this.FM(this.aM,t),e=this.aM,this.aM=null)),this.Rm(e)}FM(e,t){for(const i of e.bs())this.xs(i,t)}NM(e){const t=this.sn.Gn();for(let i=0;i{if(this.lM=!1,this.eM=0,this.aM!==null){const i=this.aM;this.aM=null,this.yM(i,t);for(const n of i.bs())if(n.ds===5&&!n.Wt.Kc(t)){this.Qt().ps(n.Wt);break}}}))}OM(){this.MM()}SM(e){this.uM.removeChild(e.fv()),e.m()}MM(){const e=this.sn.Gn(),t=e.length,i=this.nM.length;for(let n=t;n0){const o=new Nm(this,n-1,n);this.sM.push(o),this.uM.insertBefore(o.fv(),this.vM.fv())}this.uM.insertBefore(a.fv(),this.vM.fv())}for(let n=0;n{const u=h.Un().Hn(e);u!==null&&a.set(h,u)});let o;if(e!==null){const h=this.sn.Et().en(e)?.originalTime;h!==void 0&&(o=h)}const l=this.Qt().cu(),c=this.$M(n),d=function(h,u){const m=h!==null&&h.uu instanceof pi?h.uu:void 0,x=h?.bu?.te,b=u!==void 0&&u!==-1?u:void 0;return h===null||h.ee===void 0?{jM:m,qM:x}:{jM:m,qM:x,YM:{ds:h.ee,KM:(f=h.uu,v=h.ee,f instanceof Zi?"pane-primitive":v==="marker"||v==="primitive"?"series-primitive":"series"),GM:ym(h.ee,x),Y_:m,ZM:x,XM:b}};var f,v}(l,c);return{Qr:o,$n:e??void 0,JM:t??void 0,XM:c!==-1?c:void 0,jM:d.jM,QM:a,qM:d.qM,YM:d.YM,tg:i??void 0}}$M(e){let t=-1;if(e)t=this.nM.indexOf(e);else{const i=this.Qt().Vd().Kn();i!==null&&(t=this.Qt().Gn().indexOf(i))}return t}WM(e,t,i,n){this.$m.p(()=>this.UM(t,i,n,e))}HM(e,t,i,n){this.jm.p(()=>this.UM(t,i,n,e))}pM(e,t,i){this.BM(this.Qt().cu()?.gu??null),this.wd.p(()=>this.UM(e,t,i))}gM(){const e=this.yn.timeScale.visible?"":"none";this.vM.fv().style.display=e}IM(){return this.nM[0].yv().X_().N().visible}VM(){return this.nM[0].yv().J_().N().visible}mM(){return"ResizeObserver"in window&&(this.oM=new ResizeObserver(e=>{const t=e[e.length-1];if(!t)return;const i=t.contentRect.width,n=t.contentRect.height;this.wM(i,n,!0)}),this.oM.observe(this.Kv,{box:"border-box"}),!0)}xM(){this.oM!==null&&this.oM.disconnect(),this.oM=null}}function Fi(s){return!!(s.handleScroll.mouseWheel||s.handleScale.mouseWheel)}function Lm(s){return s.open===void 0&&s.value===void 0}function Am(s){return function(e){return e.open!==void 0}(s)||function(e){return e.value!==void 0}(s)}function Bn(s,e,t,i){const n=t.value,a={$n:e,wt:s,Wt:[n,n,n,n],Qr:i};return t.color!==void 0&&(a.R=t.color),a}function Om(s,e,t,i){const n=t.value,a={$n:e,wt:s,Wt:[n,n,n,n],Qr:i};return t.lineColor!==void 0&&(a.vt=t.lineColor),t.topColor!==void 0&&(a.ah=t.topColor),t.bottomColor!==void 0&&(a.oh=t.bottomColor),a}function zm(s,e,t,i){const n=t.value,a={$n:e,wt:s,Wt:[n,n,n,n],Qr:i};return t.topLineColor!==void 0&&(a._h=t.topLineColor),t.bottomLineColor!==void 0&&(a.uh=t.bottomLineColor),t.topFillColor1!==void 0&&(a.dh=t.topFillColor1),t.topFillColor2!==void 0&&(a.fh=t.topFillColor2),t.bottomFillColor1!==void 0&&(a.ph=t.bottomFillColor1),t.bottomFillColor2!==void 0&&(a.mh=t.bottomFillColor2),a}function Im(s,e,t,i){const n={$n:e,wt:s,Wt:[t.open,t.high,t.low,t.close],Qr:i};return t.color!==void 0&&(n.R=t.color),n}function $m(s,e,t,i){const n={$n:e,wt:s,Wt:[t.open,t.high,t.low,t.close],Qr:i};return t.color!==void 0&&(n.R=t.color),t.borderColor!==void 0&&(n.Ht=t.borderColor),t.wickColor!==void 0&&(n.hh=t.wickColor),n}function Dm(s,e,t,i,n){const a=_e(n)(t),o=Math.max(...a),l=Math.min(...a),c=a[a.length-1],d=[c,o,l,c],{time:h,color:u,...m}=t;return{$n:e,wt:s,Wt:d,Qr:i,ue:m,R:u}}function vt(s){return s.Wt!==void 0}function Fn(s,e){return e.customValues!==void 0&&(s.ig=e.customValues),s}function et(s){return(e,t,i,n,a,o)=>function(l,c){return c?c(l):Lm(l)}(i,o)?Fn({wt:e,$n:t,Qr:n},i):Fn(s(e,t,i,n,a),i)}function Un(s){return{Candlestick:et($m),Bar:et(Im),Area:et(Om),Baseline:et(zm),Histogram:et(Bn),Line:et(Bn),Custom:et(Dm)}[s]}function qn(s){return{$n:0,ng:new Map,Oa:s}}function Wn(s,e){if(s!==void 0&&s.length!==0)return{sg:e.key(s[0].wt),eg:e.key(s[s.length-1].wt)}}function Hn(s){let e;return s.forEach(t=>{e===void 0&&(e=t.Qr)}),_e(e)}class Bm{constructor(e){this.rg=new Map,this.hg=new Map,this.ag=new Map,this.lg=[],this.Pu=e}m(){this.rg.clear(),this.hg.clear(),this.ag.clear(),this.lg=[]}og(e,t){let i=this.rg.size!==0,n=!1;const a=this.hg.get(e);if(a!==void 0)if(this.hg.size===1)i=!1,n=!0,this.rg.clear();else for(const c of this.lg)c.pointData.ng.delete(e)&&(n=!0);let o=[];if(t.length!==0){const c=t.map(x=>x.time),d=this.Pu.createConverterToInternalObj(t),h=Un(e.bh()),u=e.ul(),m=e.cl();o=t.map((x,b)=>{const f=d(x.time),v=this.Pu.key(f);let p=this.rg.get(v);p===void 0&&(p=qn(f),this.rg.set(v,p),n=!0);const g=h(f,p.$n,x,c[b],u,m);return p.ng.set(e,g),g})}i&&this._g(),this.ug(e,o);let l=-1;if(n){const c=[];this.rg.forEach(d=>{c.push({timeWeight:0,time:d.Oa,pointData:d,originalTime:Hn(d.ng)})}),c.sort((d,h)=>this.Pu.key(d.time)-this.Pu.key(h.time)),l=this.cg(c)}return this.dg(e,l,function(c,d,h){const u=Wn(c,h),m=Wn(d,h);if(u!==void 0&&m!==void 0)return{fg:!1,Va:u.eg>=m.eg&&u.sg>=m.sg}}(this.hg.get(e),a,this.Pu))}if(e){return this.og(e,[])}pg(e,t,i){if(i&&e.Fa())throw new Error("Historical updates are not supported when conflation is enabled. Conflation requires data to be processed in order.");const n=t;(function(p){p.Qr===void 0&&(p.Qr=p.time)})(n),this.Pu.preprocessData(t);const a=this.Pu.createConverterToInternalObj([t])(t.time),o=this.ag.get(e);if(!i&&o!==void 0&&this.Pu.key(a)this.Pu.key(p.time)this.Pu.key(n.wt)?vt(t)&&i.push(t):vt(t)?i[i.length-1]=t:i.splice(-1,1),this.ag.set(e,t.wt)}vg(e,t,i){const n=this.hg.get(e);if(n===void 0)return;const a=ht(n,i,(o,l)=>o.$n{t.length!==0&&(e=Math.max(e,t[t.length-1].$n))}),e}dg(e,t,i){const n=this.Mg();if(t!==-1)this.hg.forEach((a,o)=>{n.Y_.set(o,{ue:a,bg:o===e?i:void 0})}),this.hg.has(e)||n.Y_.set(e,{ue:[],bg:i}),n.Et.Sg=this.lg,n.Et.xg=t;else{const a=this.hg.get(e);n.Y_.set(e,{ue:a||[],bg:i})}return n}Mg(){return{Y_:new Map,Et:{Dc:this.gg()}}}}function Rs(s,e){s.$n=e,s.ng.forEach(t=>{t.$n=e})}function Fm(s,e){return s._t=e-i&&s<=t+i}function Gt(s,e,t,i,n,a){const o=n-t,l=a-i;if(o===0&&l===0)return Math.hypot(s-t,e-i);const c=((s-t)*o+(e-i)*l)/(o*o+l*l),d=Math.max(0,Math.min(1,c)),h=t+o*d,u=i+l*d;return Math.hypot(s-h,e-u)}const Ui=[0,0];function qm(s,e,t){return e===void 0||e.wt!==s.wt-1?s._t-t/2:(e._t+s._t)/2}function Wm(s,e,t){return e===void 0||e.wt!==s.wt+1?s._t+t/2:(s._t+e._t)/2}function Sr(s,e,t,i,n,a,o){if(e===null||e.from>=e.to||s.length===0)return null;const l=n/2+a,c=rr(s,t-l,e.from,e.to),d=nr(s,t+l,c,e.to);if(c>=d)return null;let h=Number.POSITIVE_INFINITY;for(let u=c;ue.from?s[u-1]:void 0,b=uv)continue;o(m,Ui);const p=Ui[0],g=Ui[1],S=Math.min(p,g),j=Math.max(p,g),k=S-a,C=j+a;if(i>=S&&i<=j)h=Math.min(h,0);else if(i>=k&&i<=C){const M=Math.min(Math.abs(i-S),Math.abs(j-i));h=Math.min(h,M)}}return Number.isFinite(h)?Ds(h,0,"series-range"):null}function Hm(s,e){return s.wt0&&a=i&&(l=a-1),o>0&&o({...e,...this.ae.Sa().Sh(e.wt)}))}Ag(){this.Tg=null}Ig(){const e=this.le.Et(),t=e.N().enableConflation?e.sd():0;t!==this.Rg&&(this.yg=!0,this.Rg=t),this.yg&&(this.Lg(),this.yg=!1),this.Pg&&(this.Eg(),this.Pg=!1),this.Cg&&(this.zg(),this.Cg=!1)}zg(){const e=this.ae.Ft(),t=this.le.Et();if(this.Ag(),t.Zi()||e.Zi())return;const i=t.Ee();if(i===null||this.ae.Un().Th()===0)return;const n=this.ae.Lt();n!==null&&(this.Tg=Km(this.kg,i,this.Dg),this.Og(e,t,n.Wt),this.Ng())}}class Gm{constructor(e,t){this.Fg=e,this.Ki=t}st(e,t,i){this.Fg.draw(e,this.Ki,t,i)}}function Qm(s){switch(s){case"point":return 2;case"range":return 0;default:return 1}}class Ym extends kr{constructor(e,t,i){super(e,t,!1),this.Yh=i,this.Fg=this.Yh.renderer(),this.Vg=new Gm(this.Fg,n=>this.Wg(n))}get ga(){return this.Yh.conflationReducer}Ha(e){return this.Yh.priceValueBuilder(e)}dl(e){return this.Yh.isWhitespace(e)}Bg(e,t){const i=this.Fg.hitTest?.(e,t,o=>this.Wg(o));if(i!=null)return{ne:(n=i).distance,se:Qm(n.type),ee:"custom",gu:n.cursorStyle,te:n.objectId,ie:n.hitTestData};var n;const a=Sr(this.kg,this.Tg,e,t,this.le.Et().ml(),this.ae.N().hitTestTolerance,(o,l)=>{const c=o.Hg;let d=NaN,h=NaN;if(c!==void 0&&!this.Yh.isWhitespace(c))for(const u of this.Yh.priceValueBuilder(c)){const m=this.Wg(u);m!==null&&(d=Number.isNaN(d)?m:Math.min(d,m),h=Number.isNaN(h)?m:Math.max(h,m))}l[0]=d,l[1]=h});return a===null?null:{...a,ee:"custom"}}Lg(){const e=this.ae.Sa();this.kg=this.ae.Ua().Bh().map(t=>({wt:t.$n,_t:NaN,...e.Sh(t.$n),Hg:t.ue}))}Og(e,t){t.Ic(this.kg,ns(this.Tg))}Ng(){this.Yh.update({bars:this.kg.map(Jm),barSpacing:this.le.Et().ml(),visibleRange:this.Tg,conflationFactor:this.le.Et().sd()},this.ae.N())}Wg(e){const t=this.ae.Lt();return t===null?null:this.ae.Ft().Nt(e,t.Wt)}}function Jm(s){return{x:s._t,time:s.wt,originalData:s.Hg,barColor:s.sh}}const Xm={color:"#2196f3"},Zm=(s,e,t)=>{const i=Ge(t);return new Ym(s,e,i)};function Mr(s){const e={value:s.Wt[3],time:s.Qr};return s.ig!==void 0&&(e.customValues=s.ig),e}function Kn(s){const e=Mr(s);return s.R!==void 0&&(e.color=s.R),e}function ep(s){const e=Mr(s);return s.vt!==void 0&&(e.lineColor=s.vt),s.ah!==void 0&&(e.topColor=s.ah),s.oh!==void 0&&(e.bottomColor=s.oh),e}function tp(s){const e=Mr(s);return s._h!==void 0&&(e.topLineColor=s._h),s.uh!==void 0&&(e.bottomLineColor=s.uh),s.dh!==void 0&&(e.topFillColor1=s.dh),s.fh!==void 0&&(e.topFillColor2=s.fh),s.ph!==void 0&&(e.bottomFillColor1=s.ph),s.mh!==void 0&&(e.bottomFillColor2=s.mh),e}function fo(s){const e={open:s.Wt[0],high:s.Wt[1],low:s.Wt[2],close:s.Wt[3],time:s.Qr};return s.ig!==void 0&&(e.customValues=s.ig),e}function sp(s){const e=fo(s);return s.R!==void 0&&(e.color=s.R),e}function ip(s){const e=fo(s),{R:t,Ht:i,hh:n}=s;return t!==void 0&&(e.color=t),i!==void 0&&(e.borderColor=i),n!==void 0&&(e.wickColor=n),e}function Bs(s){return{Area:ep,Line:Kn,Baseline:tp,Histogram:Kn,Bar:sp,Candlestick:ip,Custom:rp}[s]}function rp(s){const e=s.Qr;return{...s.ue,time:e}}const np={vertLine:{color:"#9598A1",width:1,style:3,visible:!0,labelVisible:!0,labelBackgroundColor:"#131722"},horzLine:{color:"#9598A1",width:1,style:3,visible:!0,labelVisible:!0,labelBackgroundColor:"#131722"},mode:1,doNotSnapToHiddenSeriesIndices:!1},ap={vertLines:{color:"#D6DCDE",style:0,visible:!0},horzLines:{color:"#D6DCDE",style:0,visible:!0}},op={background:{type:"solid",color:"#FFFFFF"},textColor:"#191919",fontSize:12,fontFamily:Ja,panes:{enableResize:!0,separatorColor:"#E0E3EB",separatorHoverColor:"rgba(178, 181, 189, 0.2)"},attributionLogo:!0,colorSpace:"srgb",colorParsers:[]},qi={autoScale:!0,mode:0,invertScale:!1,alignLabels:!0,borderVisible:!0,borderColor:"#2B2B43",entireTextOnly:!1,visible:!1,ticksVisible:!1,scaleMargins:{bottom:.1,top:.2},minimumWidth:0,ensureEdgeTickMarksVisible:!1,tickMarkDensity:2.5},lp={rightOffset:0,barSpacing:6,minBarSpacing:.5,maxBarSpacing:0,fixLeftEdge:!1,fixRightEdge:!1,lockVisibleTimeRangeOnResize:!1,rightBarStaysOnScroll:!1,borderVisible:!0,borderColor:"#2B2B43",visible:!0,timeVisible:!1,secondsVisible:!0,shiftVisibleRangeOnNewBar:!0,allowShiftVisibleRangeOnWhitespaceReplacement:!1,ticksVisible:!1,uniformDistribution:!1,minimumHeight:0,allowBoldLabels:!0,ignoreWhitespaceIndices:!1,enableConflation:!1,conflationThresholdFactor:1,precomputeConflationOnInit:!1,precomputeConflationPriority:"background"};function Gn(){return{addDefaultPane:!0,hoveredSeriesOnTop:!0,width:0,height:0,autoSize:!1,layout:op,crosshair:np,grid:ap,overlayPriceScales:{...qi},leftPriceScale:{...qi,visible:!1},rightPriceScale:{...qi,visible:!0},defaultVisiblePriceScaleId:"right",timeScale:lp,localization:{locale:At?navigator.language:"",dateFormat:"dd MMM 'yy"},handleScroll:{mouseWheel:!0,pressedMouseMove:!0,horzTouchDrag:!0,vertTouchDrag:!0},handleScale:{axisPressedMouseMove:{time:!0,price:!0},axisDoubleClickReset:{time:!0,price:!0},mouseWheel:!0,pinch:!0},kineticScroll:{mouse:!1,touch:!0},trackingMode:{exitMode:1}}}class xo{constructor(e,t,i){this.hv=e,this.Ug=t,this.$g=i??0}applyOptions(e){this.hv.Qt().Dd(this.Ug,e,this.$g)}options(){return this.Ki().N()}width(){return ui(this.Ug)?this.hv.DM(this.Ug):0}setVisibleRange(e){this.setAutoScale(!1),this.Ki().Go(new ye(e.from,e.to))}getVisibleRange(){let e,t,i=this.Ki().ar();if(i===null)return null;if(this.Ki().ho()){const n=this.Ki().S_(),a=ho(n);i=Nt(i,this.Ki().lo()),e=Number((Math.round(i.Je()/n)*n).toFixed(a)),t=Number((Math.round(i.Qe()/n)*n).toFixed(a))}else e=i.Je(),t=i.Qe();return{from:e,to:t}}setAutoScale(e){this.applyOptions({autoScale:e})}Ki(){return P(this.hv.Qt().Id(this.Ug,this.$g)).Ft}}class cp{constructor(e,t,i,n){this.hv=e,this.yt=i,this.jg=t,this.qg=n}getHeight(){return this.yt.$t()}setHeight(e){const t=this.hv.Qt(),i=t._f(this.yt);t.Ld(i,e)}getStretchFactor(){return this.yt.F_()}setStretchFactor(e){this.yt.W_(e),this.hv.Qt().ka()}paneIndex(){return this.hv.Qt()._f(this.yt)}moveTo(e){const t=this.paneIndex();t!==e&&(me(e>=0&&ethis.jg(e))??[]}getHTMLElement(){const e=this.hv.lv();return e&&e.length!==0&&e[this.paneIndex()]?e[this.paneIndex()].fv():null}attachPrimitive(e){this.yt.ol(e),e.attached&&e.attached({chart:this.qg,requestUpdate:()=>this.yt.Qt().ka()})}detachPrimitive(e){this.yt._l(e)}priceScale(e){if(this.yt.O_(e)===null)throw new Error(`Cannot find price scale with id: ${e}`);return new xo(this.hv,e,this.paneIndex())}setPreserveEmptyPane(e){this.yt.j_(e)}preserveEmptyPane(){return this.yt.q_()}addCustomSeries(e,t={},i=0){return this.qg.addCustomSeries(e,t,i)}addSeries(e,t={}){return this.qg.addSeries(e,t,this.paneIndex())}}const dp={color:"#FF0000",price:0,lineStyle:2,lineWidth:1,lineVisible:!0,axisLabelVisible:!0,title:"",axisLabelColor:"",axisLabelTextColor:""};class Qn{constructor(e){this._r=e}applyOptions(e){this._r.vr(e)}options(){return this._r.N()}Yg(){return this._r}}class hp{constructor(e,t,i,n,a,o){this.Kg=new le,this.ae=e,this.Gg=t,this.Zg=i,this.Pu=a,this.qg=n,this.Xg=o}m(){this.Kg.m()}priceFormatter(){return this.ae.sl()}priceToCoordinate(e){const t=this.ae.Lt();return t===null?null:this.ae.Ft().Nt(e,t.Wt)}coordinateToPrice(e){const t=this.ae.Lt();return t===null?null:this.ae.Ft().Tn(e,t.Wt)}barsInLogicalRange(e){if(e===null)return null;const t=new kt(new Xt(e.from,e.to)).Uu(),i=this.ae.Un();if(i.Zi())return null;const n=i.Hn(t.Na(),1),a=i.Hn(t.bi(),-1),o=P(i.Rh()),l=P(i.Qn());if(n!==null&&a!==null&&n.$n>a.$n)return{barsBefore:e.from-o,barsAfter:l-e.to};const c={barsBefore:n===null||n.$n===o?e.from-o:n.$n-o,barsAfter:a===null||a.$n===l?l-e.to:l-a.$n};return n!==null&&a!==null&&(c.from=n.Qr,c.to=a.Qr),c}setData(e){this.Pu,this.ae.bh(),this.Gg.Jg(this.ae,e),this.Qg("full")}update(e,t=!1){this.ae.bh(),this.Gg.tb(this.ae,e,t),this.Qg("update")}pop(e=1){const t=this.Gg.ib(this.ae,e);t.length!==0&&this.Qg("update");const i=Bs(this.seriesType());return t.map(n=>i(n))}dataByIndex(e,t){const i=this.ae.Un().Hn(e,t);return i===null?null:Bs(this.seriesType())(i)}data(){const e=Bs(this.seriesType());return this.ae.Un().Bh().map(t=>e(t))}subscribeDataChanged(e){this.Kg.i(e)}unsubscribeDataChanged(e){this.Kg._(e)}applyOptions(e){this.ae.vr(e)}options(){return $e(this.ae.N())}priceScale(){return this.Zg.priceScale(this.ae.Ft().pl(),this.getPane().paneIndex())}createPriceLine(e){const t=Me($e(dp),e),i=this.ae.Ea(t);return new Qn(i)}removePriceLine(e){this.ae.Aa(e.Yg())}priceLines(){return this.ae.La().map(e=>new Qn(e))}seriesType(){return this.ae.bh()}lastValueData(e){const t=this.ae.Ae(e);return t.Le?{noData:!0}:{noData:!1,price:t.Mt,color:t.R}}attachPrimitive(e){this.ae.ol(e),e.attached&&e.attached({chart:this.qg,series:this,requestUpdate:()=>this.ae.Qt().ka(),horzScaleBehavior:this.Pu})}detachPrimitive(e){this.ae._l(e),e.detached&&e.detached(),this.ae.Qt().ka()}getPane(){const e=this.ae,t=P(this.ae.Qt().Ks(e));return this.Xg(t)}moveToPane(e){this.ae.Qt().rf(this.ae,e)}seriesOrder(){const e=this.ae.Qt().Ks(this.ae);return e===null?-1:e.Y_().indexOf(this.ae)}setSeriesOrder(e){const t=this.ae.Qt().Ks(this.ae);t!==null&&t.vu(this.ae,e)}Qg(e){this.Kg.v()&&this.Kg.p(e)}}class up{constructor(e,t,i){this.nb=new le,this.Qu=new le,this.Nw=new le,this.sn=e,this.ia=e.Et(),this.vM=t,this.ia.Zc().i(this.sb.bind(this)),this.ia.Xc().i(this.eb.bind(this)),this.vM.qw().i(this.rb.bind(this)),this.Pu=i}m(){this.ia.Zc().u(this),this.ia.Xc().u(this),this.vM.qw().u(this),this.nb.m(),this.Qu.m(),this.Nw.m()}scrollPosition(){return this.ia.Oc()}scrollToPosition(e,t){t?this.ia.Yc(e,1e3):this.sn.gs(e)}scrollToRealTime(){this.ia.qc()}getVisibleRange(){const e=this.ia.xc();return e===null?null:{from:e.from.originalTime,to:e.to.originalTime}}setVisibleRange(e){const t={from:this.Pu.convertHorzItemToInternal(e.from),to:this.Pu.convertHorzItemToInternal(e.to)},i=this.ia.kc(t);this.sn.sf(i)}getVisibleLogicalRange(){const e=this.ia.Sc();return e===null?null:{from:e.Na(),to:e.bi()}}setVisibleLogicalRange(e){me(e.from<=e.to,"The from index cannot be after the to index."),this.sn.sf(e)}resetTimeScale(){this.sn.ws()}fitContent(){this.sn.td()}logicalToCoordinate(e){const t=this.sn.Et();return t.Zi()?null:t.jt(e)}coordinateToLogical(e){return this.ia.Zi()?null:this.ia.Vc(e)}timeToIndex(e,t){const i=this.Pu.convertHorzItemToInternal(e);return this.ia.Mc(i,t)}timeToCoordinate(e){const t=this.timeToIndex(e,!1);return t===null?null:this.ia.jt(t)}coordinateToTime(e){const t=this.sn.Et(),i=t.Vc(e),n=t.en(i);return n===null?null:n.originalTime}width(){return this.vM.pv().width}height(){return this.vM.pv().height}subscribeVisibleTimeRangeChange(e){this.nb.i(e)}unsubscribeVisibleTimeRangeChange(e){this.nb._(e)}subscribeVisibleLogicalRangeChange(e){this.Qu.i(e)}unsubscribeVisibleLogicalRangeChange(e){this.Qu._(e)}subscribeSizeChange(e){this.Nw.i(e)}unsubscribeSizeChange(e){this.Nw._(e)}applyOptions(e){this.ia.vr(e)}options(){return{...$e(this.ia.N()),barSpacing:this.ia.ml()}}sb(){this.nb.v()&&this.nb.p(this.getVisibleRange())}eb(){this.Qu.v()&&this.Qu.p(this.getVisibleLogicalRange())}rb(e){this.Nw.p(e.width,e.height)}}function Yn(s){return function(e){if(Ns(e.handleScale)){const i=e.handleScale;e.handleScale={axisDoubleClickReset:{time:i,price:i},axisPressedMouseMove:{time:i,price:i},mouseWheel:i,pinch:i}}else if(e.handleScale!==void 0){const{axisPressedMouseMove:i,axisDoubleClickReset:n}=e.handleScale;Ns(i)&&(e.handleScale.axisPressedMouseMove={time:i,price:i}),Ns(n)&&(e.handleScale.axisDoubleClickReset={time:n,price:n})}const t=e.handleScroll;Ns(t)&&(e.handleScroll={horzTouchDrag:t,vertTouchDrag:t,mouseWheel:t,pressedMouseMove:t})}(s),s}class mp{constructor(e,t,i){this.hb=new Map,this.ab=new Map,this.lb=new le,this.ob=new le,this._b=new le,this.dd=new WeakMap,this.ub=new Bm(t);const n=i===void 0?$e(Gn()):Me($e(Gn()),Yn(i));this.cb=t,this.hv=new Pm(e,n,t),this.hv.mw().i(o=>{this.lb.v()&&this.lb.p(this.fb(o()))},this),this.hv.ww().i(o=>{this.ob.v()&&this.ob.p(this.fb(o()))},this),this.hv.Bd().i(o=>{this._b.v()&&this._b.p(this.fb(o()))},this);const a=this.hv.Qt();this.pb=new up(a,this.hv.bM(),this.cb)}remove(){this.hv.mw().u(this),this.hv.ww().u(this),this.hv.Bd().u(this),this.pb.m(),this.hv.m(),this.hb.clear(),this.ab.clear(),this.lb.m(),this.ob.m(),this._b.m(),this.ub.m()}resize(e,t,i){this.autoSizeActive()||this.hv.wM(e,t,i)}addCustomSeries(e,t={},i=0){const n=(a=>({type:"Custom",isBuiltIn:!1,defaultOptions:{...Xm,...a.defaultOptions()},mb:Zm,wb:a}))(Ge(e));return this.Mb(n,t,i)}addSeries(e,t={},i=0){return this.Mb(e,t,i)}removeSeries(e){const t=_e(this.hb.get(e)),i=this.ub.if(t);this.hv.Qt().if(t),this.gb(i),this.hb.delete(e),this.ab.delete(t)}Jg(e,t){this.gb(this.ub.og(e,t))}tb(e,t,i){this.gb(this.ub.pg(e,t,i))}ib(e,t){const[i,n]=this.ub.wg(e,t);return i.length!==0&&this.gb(n),i}subscribeClick(e){this.lb.i(e)}unsubscribeClick(e){this.lb._(e)}subscribeCrosshairMove(e){this._b.i(e)}unsubscribeCrosshairMove(e){this._b._(e)}subscribeDblClick(e){this.ob.i(e)}unsubscribeDblClick(e){this.ob._(e)}priceScale(e,t=0){return new xo(this.hv,e,t)}timeScale(){return this.pb}applyOptions(e){this.hv.vr(Yn(e))}options(){return this.hv.N()}takeScreenshot(e=!1,t=!1){let i,n;try{t||(i=this.hv.Qt().N().crosshair.mode,this.hv.vr({crosshair:{mode:2}})),n=this.hv.TM(e)}finally{t||i===void 0||this.hv.Qt().vr({crosshair:{mode:i}})}return n}addPane(e=!1){const t=this.hv.Qt().uf();return t.j_(e),this.bb(t)}removePane(e){this.hv.Qt().Ad(e)}swapPanes(e,t){this.hv.Qt().zd(e,t)}autoSizeActive(){return this.hv.CM()}chartElement(){return this.hv.Mv()}panes(){return this.hv.Qt().Gn().map(e=>this.bb(e))}paneSize(e=0){const t=this.hv.AM(e);return{height:t.height,width:t.width}}setCrosshairPosition(e,t,i){const n=this.hb.get(i);if(n===void 0)return;const a=this.hv.Qt().Ks(n);a!==null&&this.hv.Qt().Gd(e,t,a)}clearCrosshairPosition(){this.hv.Qt().Zd(!0)}horzBehaviour(){return this.cb}Mb(e,t={},i=0){me(e.mb!==void 0),function(c){if(c===void 0||c.type==="custom")return;const d=c;d.minMove!==void 0&&d.precision===void 0&&(d.precision=ho(d.minMove))}(t.priceFormat),e.type==="Candlestick"&&function(c){c.borderColor!==void 0&&(c.borderUpColor=c.borderColor,c.borderDownColor=c.borderColor),c.wickColor!==void 0&&(c.wickUpColor=c.wickColor,c.wickDownColor=c.wickColor)}(t);const n=Me($e(Qa),$e(e.defaultOptions),t),a=e.mb,o=new pi(this.hv.Qt(),e.type,n,a,e.wb);this.hv.Qt().Qd(o,i);const l=new hp(o,this,this,this,this.cb,c=>this.bb(c));return this.hb.set(l,o),this.ab.set(o,l),l}gb(e){const t=this.hv.Qt();for(const i of e.Y_.keys())i.Ia();t.Xd(e.Et.Dc,e.Et.Sg,e.Et.xg),e.Y_.forEach((i,n)=>n.ht(i.ue,i.bg)),t.Et().dc(),t.Lc()}Sb(e){return _e(this.ab.get(e))}xb(e){return e!==void 0&&this.ab.has(e)?this.Sb(e):void 0}fb(e){const t=new Map;e.QM.forEach((a,o)=>{const l=o.bh(),c=Bs(l)(a);if(l!=="Custom")me(Am(c));else{const d=o.cl();me(!d||d(c)===!1)}t.set(this.Sb(o),c)});const i=this.xb(e.jM),n=e.YM===void 0?void 0:{type:e.YM.ds,sourceKind:e.YM.KM,objectKind:e.YM.GM,series:this.xb(e.YM.Y_),objectId:e.YM.ZM,paneIndex:e.YM.XM};return{time:e.Qr,logical:e.$n,point:e.JM,paneIndex:e.XM,hoveredInfo:n,hoveredSeries:i,hoveredObjectId:e.qM,seriesData:t,sourceEvent:e.tg}}bb(e){let t=this.dd.get(e);return t||(t=new cp(this.hv,i=>this.Sb(i),e,this),this.dd.set(e,t)),t}}function pp(s){if(fs(s)){const e=document.getElementById(s);return me(e!==null,`Cannot find element in DOM with id=${s}`),e}return s}function fp(s,e,t){const i=pp(s),n=new mp(i,e,t);return e.setOptions(n.options()),n}function xi(s,e){return fp(s,new Ln,Ln.Tf(e))}function Ht(s,e,t,i){return Math.hypot(t-s,i-e)}function bo(s,e,t,i,n,a,o,l=0){if(e.length===0||i.from>=e.length||i.to<=0)return;const{context:c,horizontalPixelRatio:d,verticalPixelRatio:h}=s,u=e[i.from];let m=a(s,u),x=u;if(i.to-i.from<2){const b=n/2;c.beginPath();const f={_t:u._t-b,ut:u.ut},v={_t:u._t+b,ut:u.ut};c.moveTo(f._t*d,f.ut*h),c.lineTo(v._t*d,v.ut*h),o(s,m,f,v)}else{const b=l>0;let f=0;const v=(g,S)=>{if(o(s,m,x,S),c.beginPath(),m=g,x=S,b){const j=f%l;c.lineDashOffset=j,f=j}};let p=x;c.beginPath(),c.moveTo(u._t*d,u.ut*h);for(let g=i.from+1;gb+f,0)}(h);a!==void 0&&bo(e,t,a,i,n,u,xp,m),c&&function(x,b,f,v,p){if(v.to-v.from<=0)return;const{horizontalPixelRatio:g,verticalPixelRatio:S,context:j}=x;let k=null;const C=Math.max(1,Math.floor(g))%2/2,M=f*S+C;for(let L=v.to-1;L>=v.from;--L){const I=b[L];if(I){const R=p(x,I);R!==k&&(k!==null&&j.fill(),j.beginPath(),j.fillStyle=R,k=R);const T=Math.round(I._t*g)+C,E=I.ut*S;j.moveTo(T,E),j.arc(T,E,M,0,2*Math.PI)}}j.fill()}(e,t,c,i,u)}}class go extends bp{kb(e,t){return t.vt}}function Zn(s,e,t,i,n){const a=1-n;return a*a*a*s+3*a*a*n*e+3*a*n*n*t+n*n*n*i}function gp(s,e,t,i,n){if(t===2){const[a,o]=Cr(i,n-1,n);return[Math.min(s._t,e._t,a._t,o._t),Math.max(s._t,e._t,a._t,o._t)]}return[Math.min(s._t,e._t),Math.max(s._t,e._t)]}function vp(s,e,t,i,n,a,o,l){switch(n){case 1:{const c=Gt(s,e,t._t,t.ut,i._t,t.ut),d=Gt(s,e,i._t,t.ut,i._t,i.ut),h=Math.min(c,d);return h<=l?h:null}case 2:{const[c,d]=Cr(a,o-1,o),h=function(u,m,x){let b=Number.POSITIVE_INFINITY,f=x[0];for(let v=1;v<=12;v++){const p=v/12,g={_t:Zn(x[0]._t,x[1]._t,x[2]._t,x[3]._t,p),ut:Zn(x[0].ut,x[1].ut,x[2].ut,x[3].ut,p)};b=Math.min(b,Gt(u,m,f._t,f.ut,g._t,g.ut)),f=g}return b}(s,e,[t,c,d,i]);return h<=l?h:null}default:{const c=Gt(s,e,t._t,t.ut,i._t,i.ut);return c<=l?c:null}}}class vo extends kr{constructor(e,t){super(e,t,!0)}Og(e,t,i){t.Ic(this.kg,ns(this.Tg)),e.Jo(this.kg,i,ns(this.Tg))}Tb(e,t){return{wt:e,Mt:t,_t:NaN,ut:NaN}}Lg(){const e=this.ae.Sa();this.kg=this.ae.Ua().Bh().map(t=>{let i;if((t.Gr??1)>1){const n=t.Wt[1],a=t.Wt[2],o=t.Wt[3];i=Math.abs(n-o)>Math.abs(a-o)?n:a}else i=t.Wt[3];return this.Rb(t.$n,i,e)})}}class yo extends vo{Bg(e,t){const i=this.ae.N();return function(n,a,o,l,c,d,h,u=0,m=0){if(a===null||a.from>=a.to||n.length===0)return null;const x=Math.max(d/2,h??0)+m;let b=Number.POSITIVE_INFINITY;if(h!==void 0){const j=h+m,k=rr(n,o-j,a.from,a.to),C=nr(n,o+j,k,a.to);for(let M=k;Mnew yp(s,e)};function Np(s,e,t,i,n){const{context:a,horizontalPixelRatio:o,verticalPixelRatio:l}=e;a.lineTo(n._t*o,s*l),a.lineTo(i._t*o,s*l),a.closePath(),a.fillStyle=t,a.fill()}class jp extends Ue{constructor(){super(...arguments),this.rt=null}ht(e){this.rt=e}et(e){if(this.rt===null)return;const{ot:t,lt:i,Cb:n,ct:a,Gt:o,yb:l}=this.rt,c=this.rt.Lb??(this.rt.zb?0:e.mediaSize.height);if(i===null)return;const d=e.context;d.lineCap="butt",d.lineJoin="round",d.lineWidth=a,Xe(d,o),d.lineWidth=1,bo(e,t,l,i,n,this.Ob.bind(this),Np.bind(null,c))}}class _p{Nb(e,t){const i=this.Fb,{Wb:n,Hb:a,Ub:o,$b:l,Lb:c,jb:d,qb:h}=t;if(this.Yb===void 0||i===void 0||i.Wb!==n||i.Hb!==a||i.Ub!==o||i.$b!==l||i.Lb!==c||i.jb!==d||i.qb!==h){const{verticalPixelRatio:u}=e,m=c||d>0?u:1,x=d*m,b=h===e.bitmapSize.height?h:h*m,f=(c??0)*m,v=e.context.createLinearGradient(0,x,0,b);if(v.addColorStop(0,n),c!=null){const p=St((f-x)/(b-x),0,1);v.addColorStop(p,a),v.addColorStop(p,o)}v.addColorStop(1,l),this.Yb=v,this.Fb=t}return this.Yb}}class Sp{constructor(e,t,i,n){this.Zb=e,this.Xb=t,this.Jb=i,this.Qb=n}st(e,t,i){this.Zb.st(e,t,i),!this.Jb()||t&&this.Qb()||this.Xb.st(e,t,i)}}class kp{constructor(e,t){this.Xb=e,this.tS=t}Tt(){return this.tS()?this.Xb:null}}class Mp extends jp{constructor(){super(...arguments),this.Kb=new _p}Ob(e,t){return this.Kb.Nb(e,{Wb:t.ah,Hb:"",Ub:"",$b:t.oh,jb:this.rt?.jb??0,qb:e.bitmapSize.height})}}class Cp extends yo{constructor(e,t){super(e,t),this.lS=new Mp,this.Xb=new go,this.sS=new kp(this.Xb,()=>this.Jb()),this.eS=[this],this.rS=[this.sS],this.hS={Za:this.eS,qa:this.rS},this.Vg=new Sp(this.lS,this.Xb,()=>this.Jb(),()=>this.le.N().hoveredSeriesOnTop)}Ga(){return this.hS}Rb(e,t,i){return{...this.Tb(e,t),...i.Sh(e)}}Ng(){const e=this.ae.N();if(this.Tg===null||this.kg.length===0)return;let t;if(e.relativeGradient){t=this.kg[this.Tg.from].ut;for(let i=this.Tg.from;inew Cp(s,e)};class Tp extends kr{constructor(e,t){super(e,t,!1)}Bg(e,t){return Sr(this.kg,this.Tg,e,t,this.le.Et().ml(),this.ae.N().hitTestTolerance,(i,n)=>{n[0]=i.n_,n[1]=i.s_})}Og(e,t,i){t.Ic(this.kg,ns(this.Tg)),e.t_(this.kg,i,ns(this.Tg))}fS(e,t,i){return{wt:e,jr:t.Wt[0],qr:t.Wt[1],Yr:t.Wt[2],Kr:t.Wt[3],_t:NaN,i_:NaN,n_:NaN,s_:NaN,e_:NaN}}Lg(){const e=this.ae.Sa();this.kg=this.ae.Ua().Bh().map(t=>this.Rb(t.$n,t,e))}}class Rp extends Ue{constructor(){super(...arguments),this.qt=null,this.oS=0}ht(e){this.qt=e}et(e){if(this.qt===null||this.qt.Un.length===0||this.qt.lt===null)return;const{horizontalPixelRatio:t}=e;this.oS=function(a,o){if(a>=2.5&&a<=4)return Math.floor(3*o);const l=1-.2*Math.atan(Math.max(4,a)-4)/(.5*Math.PI),c=Math.floor(a*l*o),d=Math.floor(a*o),h=Math.min(c,d);return Math.max(Math.floor(o),h)}(this.qt.ml,t),this.oS>=2&&Math.floor(t)%2!=this.oS%2&&this.oS--;const i=this.qt.Un;this.qt.pS&&this.vS(e,i,this.qt.lt),this.qt.gi&&this.Vm(e,i,this.qt.lt);const n=this.mS(t);(!this.qt.gi||this.oS>2*n)&&this.wS(e,i,this.qt.lt)}vS(e,t,i){if(this.qt===null)return;const{context:n,horizontalPixelRatio:a,verticalPixelRatio:o}=e;let l="",c=Math.min(Math.floor(a),Math.floor(this.qt.ml*a));c=Math.max(Math.floor(a),Math.min(c,this.oS));const d=Math.floor(.5*c);let h=null;for(let u=i.from;u2*c)gu(n,m,b,x-m+1,f-b+1,c);else{const v=x-m+1;n.fillRect(m,b,v,f-b+1)}d=x}}wS(e,t,i){if(this.qt===null)return;const{context:n,horizontalPixelRatio:a,verticalPixelRatio:o}=e;let l="";const c=this.mS(a);for(let d=i.from;dm||n.fillRect(x,u,b-x+1,m-u+1)}}}class Pp extends Tp{constructor(){super(...arguments),this.Vg=new Rp}Rb(e,t,i){return{...this.fS(e,t,i),...i.Sh(e)}}Ng(){const e=this.ae.N();this.Vg.ht({Un:this.kg,ml:this.le.Et().ml(),pS:e.wickVisible,gi:e.borderVisible,lt:this.Tg})}}const Lp={type:"Candlestick",isBuiltIn:!0,defaultOptions:{upColor:"#26a69a",downColor:"#ef5350",wickVisible:!0,borderVisible:!0,borderColor:"#378658",borderUpColor:"#26a69a",borderDownColor:"#ef5350",wickColor:"#737375",wickUpColor:"#26a69a",wickDownColor:"#ef5350"},mb:(s,e)=>new Pp(s,e)};class Ap extends Ue{constructor(){super(...arguments),this.qt=null,this.MS=[]}ht(e){this.qt=e,this.MS=[]}et({context:e,horizontalPixelRatio:t,verticalPixelRatio:i}){if(this.qt===null||this.qt.ot.length===0||this.qt.lt===null)return;this.MS.length||this.gS(t);const n=Math.max(1,Math.floor(i)),a=Math.round(this.qt.bS*i)-Math.floor(n/2),o=a+n;for(let l=this.qt.lt.from;ll.ce?l.bi=o.Na-t-1:o.Na=l.bi+t+1)}let n=Math.ceil(this.qt.ml*e);for(let a=this.qt.lt.from;a0&&n<4)for(let a=this.qt.lt.from;an&&(o.SS>o.ce?o.bi-=1:o.Na+=1)}}}class Op extends vo{constructor(){super(...arguments),this.Vg=new Ap}Bg(e,t){const i=this.ae.Ft().Nt(this.ae.N().base,P(this.ae.Lt()).Wt);return i===null?null:Sr(this.kg,this.Tg,e,t,this.le.Et().ml(),this.ae.N().hitTestTolerance,(n,a)=>{a[0]=n.ut,a[1]=i})}Rb(e,t,i){return{...this.Tb(e,t),...i.Sh(e)}}Ng(){const e={ot:this.kg,ml:this.le.Et().ml(),lt:this.Tg,bS:this.ae.Ft().Nt(this.ae.N().base,P(this.ae.Lt()).Wt)};this.Vg.ht(e)}}const Er={type:"Histogram",isBuiltIn:!0,defaultOptions:{color:"#26a69a",base:0},mb:(s,e)=>new Op(s,e)};({...Qa});function zp(s){return!s||isNaN(s)||s<=0?{type:"price",precision:2,minMove:.01}:s<1e-5?{type:"price",precision:8,minMove:1e-8}:s<.001?{type:"price",precision:6,minMove:1e-6}:s<.1?{type:"price",precision:5,minMove:1e-5}:s<1?{type:"price",precision:4,minMove:1e-4}:s<10?{type:"price",precision:3,minMove:.001}:{type:"price",precision:2,minMove:.01}}function Ps(s){return s==null||isNaN(s)?"-":s>=1e3?s.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):s>=1?s.toFixed(4):s>=.01?s.toFixed(6):s.toFixed(8)}function Ip({candles:s,symbol:e,overlays:t,height:i=520,isLoading:n=!1}){const a=y.useRef(null),o=y.useRef(null),l=y.useRef(null),c=y.useRef(null),d=y.useRef([]),h=y.useRef(!1),u=y.useRef(e),m=y.useRef(null),[x,b]=y.useState(null);y.useEffect(()=>{if(!a.current)return;const p=xi(a.current,{width:a.current.clientWidth,height:i,layout:{background:{type:Lt.Solid,color:"#090b0e"},textColor:"#94a3b8",fontSize:11,fontFamily:"JetBrains Mono, ui-monospace, SFMono-Regular, monospace"},grid:{vertLines:{color:"rgba(30, 41, 59, 0.4)",style:de.SparseDotted},horzLines:{color:"rgba(30, 41, 59, 0.4)",style:de.SparseDotted}},crosshair:{mode:Pt.Normal,vertLine:{color:"#38bdf8",width:1,style:de.Dashed,labelBackgroundColor:"#0284c7"},horzLine:{color:"#38bdf8",width:1,style:de.Dashed,labelBackgroundColor:"#0284c7"}},rightPriceScale:{borderColor:"#1e293b",autoScale:!0,scaleMargins:{top:.1,bottom:.22}},timeScale:{borderColor:"#1e293b",timeVisible:!0,secondsVisible:!1}});o.current=p;const g=p.addSeries(Lp,{upColor:"#10b981",downColor:"#ef4444",borderVisible:!1,wickUpColor:"#10b981",wickDownColor:"#ef4444",priceFormat:{type:"price",precision:2,minMove:.01}});l.current=g;const S=p.addSeries(Er,{color:"#64748b",priceFormat:{type:"volume"},priceScaleId:"volume"});p.priceScale("volume").applyOptions({scaleMargins:{top:.8,bottom:0},visible:!1}),c.current=S,p.subscribeCrosshairMove(C=>{if(!C.time||!C.seriesData){b(null);return}const M=C.seriesData.get(g),L=C.seriesData.get(S);M&&b({time:Number(C.time),open:M.open,high:M.high,low:M.low,close:M.close,volume:L?.value})});const j=()=>{a.current&&o.current&&o.current.applyOptions({width:a.current.clientWidth})};window.addEventListener("resize",j);const k=new ResizeObserver(j);return k.observe(a.current),()=>{window.removeEventListener("resize",j),k.disconnect(),p.remove(),o.current=null,l.current=null,c.current=null}},[i]),y.useEffect(()=>{if(u.current!==e){u.current=e,m.current=null,h.current=!1,b(null);try{l.current?.setData([]),c.current?.setData([])}catch{}d.current.forEach(p=>{try{l.current?.removePriceLine(p)}catch{}}),d.current=[]}},[e]),y.useEffect(()=>{if(!l.current||!c.current||!s||s.length===0)return;const p=new Map;for(const T of s)T&&T.time&&!isNaN(T.time)&&!isNaN(T.close)&&T.close>0&&!isNaN(T.open)&&!isNaN(T.high)&&!isNaN(T.low)&&p.set(T.time,T);const g=Array.from(p.values()).sort((T,E)=>T.time-E.time);if(g.length===0)return;const S=Math.floor(g.length/2),j=g[S]?.close||g[0].close,k=g.filter(T=>{if(j>0){const E=T.close/j;return E>=.1&&E<=10}return!0});if(k.length===0)return;const C=k[0].time,M=m.current!==C,L=!h.current||M,I=k[k.length-1],R=zp(I.close);if(l.current.applyOptions({priceFormat:R}),L){m.current=C;const T=k.map(F=>({time:F.time,open:F.open,high:F.high,low:F.low,close:F.close})),E=k.map(F=>({time:F.time,value:F.volume||0,color:F.close>=F.open?"rgba(16, 185, 129, 0.35)":"rgba(239, 68, 68, 0.35)"}));try{l.current.setData(T),c.current.setData(E),o.current?.timeScale().fitContent(),h.current=!0}catch{}}else{const T=k[k.length-1];try{l.current.update({time:T.time,open:T.open,high:T.high,low:T.low,close:T.close}),c.current.update({time:T.time,value:T.volume||0,color:T.close>=T.open?"rgba(16, 185, 129, 0.35)":"rgba(239, 68, 68, 0.35)"})}catch{const F=k.map(z=>({time:z.time,open:z.open,high:z.high,low:z.low,close:z.close})),B=k.map(z=>({time:z.time,value:z.volume||0,color:z.close>=z.open?"rgba(16, 185, 129, 0.35)":"rgba(239, 68, 68, 0.35)"}));try{l.current.setData(F),c.current.setData(B),o.current?.timeScale().fitContent()}catch{}}}},[s,e]),y.useEffect(()=>{if(!l.current)return;d.current.forEach(M=>{try{l.current?.removePriceLine(M)}catch{}}),d.current=[];const p=l.current,g=t?.showLevels!==!1,S=t?.showMagnets!==!1,k=(s&&s.length>0?s[s.length-1]:null)?.close||0,C=M=>{if(!M||isNaN(M)||M<=0)return!1;if(k>0){const L=M/k;return L>=.2&&L<=5}return!0};if(g&&t?.entryPrice&&C(t.entryPrice)){const M=p.createPriceLine({price:t.entryPrice,color:"#38bdf8",lineWidth:2,lineStyle:de.Dashed,axisLabelVisible:!0,title:"ENTRY ZONE"});d.current.push(M)}if(g&&t?.stopLoss&&C(t.stopLoss)){const M=p.createPriceLine({price:t.stopLoss,color:"#f43f5e",lineWidth:2,lineStyle:de.Dashed,axisLabelVisible:!0,title:"STOP LOSS"});d.current.push(M)}if(g&&t?.takeProfit1&&C(t.takeProfit1)){const M=p.createPriceLine({price:t.takeProfit1,color:"#10b981",lineWidth:2,lineStyle:de.Dashed,axisLabelVisible:!0,title:"TP1 (50%)"});d.current.push(M)}if(g&&t?.takeProfit2&&C(t.takeProfit2)){const M=p.createPriceLine({price:t.takeProfit2,color:"#34d399",lineWidth:2,lineStyle:de.Dashed,axisLabelVisible:!0,title:"TP2 (RUNNER)"});d.current.push(M)}if(g&&t?.invalidation&&C(t.invalidation)){const M=p.createPriceLine({price:t.invalidation,color:"#fbbf24",lineWidth:1,lineStyle:de.Dotted,axisLabelVisible:!0,title:"INVALIDATION"});d.current.push(M)}if(S&&t?.upperMagnet&&C(t.upperMagnet)){const M=p.createPriceLine({price:t.upperMagnet,color:"#a855f7",lineWidth:1,lineStyle:de.Dotted,axisLabelVisible:!0,title:"🧲 LIQ MAGNET UPPER"});d.current.push(M)}if(S&&t?.lowerMagnet&&C(t.lowerMagnet)){const M=p.createPriceLine({price:t.lowerMagnet,color:"#a855f7",lineWidth:1,lineStyle:de.Dotted,axisLabelVisible:!0,title:"🧲 LIQ MAGNET LOWER"});d.current.push(M)}},[t,s,e]);const f=s&&s.length>0?s[s.length-1]:null,v=x||f;return r.jsxs("div",{className:"relative w-full rounded-2xl bg-[#090b0e] border border-border/80 overflow-hidden shadow-2xl flex flex-col",children:[r.jsxs("div",{className:"px-4 py-2.5 bg-bg-card/90 border-b border-border/60 flex flex-wrap items-center justify-between gap-3 text-xs font-mono",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"font-bold text-text-primary text-sm tracking-wide",children:e}),v&&r.jsxs("div",{className:"hidden sm:flex items-center gap-2.5 text-[11px]",children:[r.jsxs("span",{className:"text-text-muted",children:["O: ",r.jsx("span",{className:"text-text-primary",children:Ps(v.open)})]}),r.jsxs("span",{className:"text-text-muted",children:["H: ",r.jsx("span",{className:"text-text-primary",children:Ps(v.high)})]}),r.jsxs("span",{className:"text-text-muted",children:["L: ",r.jsx("span",{className:"text-text-primary",children:Ps(v.low)})]}),r.jsxs("span",{className:"text-text-muted",children:["C:"," ",r.jsx("span",{className:v.close&&v.open&&v.close>=v.open?"text-emerald-400 font-semibold":"text-rose-400 font-semibold",children:Ps(v.close)})]}),v.volume!==void 0&&r.jsxs("span",{className:"text-text-muted",children:["Vol: ",r.jsx("span",{className:"text-text-secondary",children:Math.round(v.volume).toLocaleString()})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2 text-[10px]",children:[t?.showLevels!==!1&&r.jsxs("span",{className:"flex items-center gap-1 text-sky-400 bg-sky-500/10 px-2 py-0.5 rounded border border-sky-500/20",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-sky-400"})," Levels Sinyal"]}),t?.showMagnets!==!1&&r.jsxs("span",{className:"flex items-center gap-1 text-purple-400 bg-purple-500/10 px-2 py-0.5 rounded border border-purple-500/20",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-purple-400"})," Likuidasi Magnet"]})]})]}),r.jsxs("div",{className:"relative w-full flex-1 min-h-[420px]",children:[r.jsx("div",{ref:a,className:"w-full h-full min-h-[420px]"}),n&&r.jsxs("div",{className:"absolute inset-0 bg-[#090b0e]/80 backdrop-blur-sm flex flex-col items-center justify-center gap-2.5 z-10 font-mono text-xs text-text-muted",children:[r.jsx(Ko,{className:"w-6 h-6 animate-spin text-accent-blue"}),r.jsxs("span",{children:["Memuat data candlestick ",e,"..."]})]}),!n&&(!s||s.length===0)&&r.jsxs("div",{className:"absolute inset-0 bg-[#090b0e]/90 flex flex-col items-center justify-center gap-2 z-10 font-mono text-xs text-text-muted",children:[r.jsx(ar,{className:"w-6 h-6 text-amber-400"}),r.jsxs("span",{children:["Data grafik untuk ",e," sedang dimuat atau belum tersedia"]})]})]})]})}function $p(s){if(isNaN(s)||s===0)return"0";const e=s>0?"+":"",t=Math.abs(s);return t>=1e9?`${e}${(s/1e9).toFixed(2)}B`:t>=1e6?`${e}${(s/1e6).toFixed(2)}M`:t>=1e3?`${e}${s.toLocaleString("en-US",{minimumFractionDigits:1,maximumFractionDigits:2})}`:`${e}${s.toFixed(2)}`}function Dp({candles:s,symbol:e,height:t=180}){const i=y.useRef(null),n=y.useRef(null),a=y.useRef(null),o=y.useRef(null),l=y.useRef(!1),c=y.useRef(null),d=y.useRef(e);y.useEffect(()=>{if(!i.current)return;const m=xi(i.current,{width:i.current.clientWidth,height:t,layout:{background:{type:Lt.Solid,color:"#090b0e"},textColor:"#94a3b8",fontSize:10,fontFamily:"JetBrains Mono, ui-monospace, monospace"},grid:{vertLines:{color:"rgba(30, 41, 59, 0.3)",style:de.SparseDotted},horzLines:{color:"rgba(30, 41, 59, 0.3)",style:de.SparseDotted}},crosshair:{mode:Pt.Normal},rightPriceScale:{borderColor:"#1e293b",autoScale:!0},timeScale:{borderColor:"#1e293b",timeVisible:!0,secondsVisible:!1}});n.current=m;const x=m.addSeries(Er,{color:"#38bdf8",priceFormat:{type:"volume"},priceScaleId:"right"});o.current=x;const b=m.addSeries(wp,{color:"#f59e0b",lineWidth:2,crosshairMarkerVisible:!0});a.current=b;const f=()=>{i.current&&n.current&&n.current.applyOptions({width:i.current.clientWidth})};window.addEventListener("resize",f);const v=new ResizeObserver(f);return v.observe(i.current),()=>{window.removeEventListener("resize",f),v.disconnect(),m.remove(),n.current=null,a.current=null,o.current=null}},[t]),y.useEffect(()=>{if(d.current!==e){d.current=e,c.current=null,l.current=!1;try{a.current?.setData([]),o.current?.setData([])}catch{}}},[e]),y.useEffect(()=>{if(!a.current||!o.current||!s||s.length===0)return;const m=new Map;for(const p of s)p&&p.time&&!isNaN(p.time)&&m.set(p.time,p);const x=Array.from(m.values()).sort((p,g)=>p.time-g.time);if(x.length===0)return;const b=x[0].time,f=c.current!==b;if(!l.current||f){c.current=b;const p=x.filter(S=>S.cvd!==void 0&&!isNaN(S.cvd)).map(S=>({time:S.time,value:S.cvd})),g=x.filter(S=>S.delta!==void 0&&!isNaN(S.delta)).map(S=>({time:S.time,value:S.delta,color:(S.delta||0)>=0?"rgba(16, 185, 129, 0.65)":"rgba(239, 68, 68, 0.65)"}));try{a.current.setData(p),o.current.setData(g),n.current?.timeScale().fitContent(),l.current=!0}catch{}}else{const p=x[x.length-1];if(p.cvd!==void 0&&!isNaN(p.cvd))try{a.current.update({time:p.time,value:p.cvd})}catch{}if(p.delta!==void 0&&!isNaN(p.delta))try{o.current.update({time:p.time,value:p.delta,color:(p.delta||0)>=0?"rgba(16, 185, 129, 0.65)":"rgba(239, 68, 68, 0.65)"})}catch{}}},[s,e]);const h=s[s.length-1]?.cvd??0,u=h>=0;return r.jsxs("div",{className:"w-full rounded-2xl bg-[#090b0e] border border-border/80 overflow-hidden shadow-xl flex flex-col",children:[r.jsxs("div",{className:"px-4 py-2 bg-bg-card/80 border-b border-border/60 flex items-center justify-between text-xs font-mono",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-400"}),r.jsx("span",{className:"font-semibold text-text-primary text-[11px] tracking-wide",children:"Cumulative Volume Delta (CVD) & Bar Delta"})]}),r.jsxs("div",{className:"flex items-center gap-3 text-[11px]",children:[r.jsx("span",{className:"text-text-muted",children:"Net Cumulative:"}),r.jsx("span",{className:`font-bold ${u?"text-emerald-400":"text-rose-400"}`,title:`Exact CVD: ${h.toLocaleString()}`,children:$p(h)})]})]}),r.jsx("div",{ref:i,className:"w-full flex-1 min-h-[160px]"})]})}function ea(s){return!s||isNaN(s)||s<=0?"$0":s>=1e9?`$${(s/1e9).toFixed(2)}B`:s>=1e6?`$${(s/1e6).toFixed(2)}M`:s>=1e3?`$${(s/1e3).toFixed(1)}K`:`$${s.toFixed(2)}`}function Bp({candles:s,symbol:e,height:t=190,exchangesIncluded:i=["binance","bybit"]}){const n=y.useRef(null),a=y.useRef(null),o=y.useRef(null),l=y.useRef(!1),c=y.useRef(null),d=y.useRef(e);y.useEffect(()=>{if(!n.current)return;const f=xi(n.current,{width:n.current.clientWidth,height:t,layout:{background:{type:Lt.Solid,color:"#090b0e"},textColor:"#94a3b8",fontSize:10,fontFamily:"JetBrains Mono, ui-monospace, monospace"},grid:{vertLines:{color:"rgba(30, 41, 59, 0.3)",style:de.SparseDotted},horzLines:{color:"rgba(30, 41, 59, 0.3)",style:de.SparseDotted}},crosshair:{mode:Pt.Normal},rightPriceScale:{borderColor:"#1e293b",autoScale:!0},timeScale:{borderColor:"#1e293b",timeVisible:!0,secondsVisible:!1}});a.current=f;const v=f.addSeries(Ep,{topColor:"rgba(56, 189, 248, 0.35)",bottomColor:"rgba(56, 189, 248, 0.02)",lineColor:"#38bdf8",lineWidth:2,crosshairMarkerVisible:!0,priceFormat:{type:"custom",formatter:S=>ea(S)}});o.current=v;const p=()=>{n.current&&a.current&&a.current.applyOptions({width:n.current.clientWidth})};window.addEventListener("resize",p);const g=new ResizeObserver(p);return g.observe(n.current),()=>{window.removeEventListener("resize",p),g.disconnect(),f.remove(),a.current=null,o.current=null}},[t]),y.useEffect(()=>{if(d.current!==e){d.current=e,c.current=null,l.current=!1;try{o.current?.setData([])}catch{}}},[e]),y.useEffect(()=>{if(!o.current||!s||s.length===0)return;const f=new Map;for(const k of s)k&&k.time&&!isNaN(k.time)&&f.set(k.time,k);const v=Array.from(f.values()).sort((k,C)=>k.time-C.time);if(v.length===0)return;const p=v.filter(k=>k.open_interest!==void 0&&k.open_interest!==null&&!isNaN(k.open_interest)&&k.open_interest>0).map(k=>({time:k.time,value:k.open_interest}));if(p.length===0)return;const g=p[0].time,S=c.current!==g;if(!l.current||S){c.current=g;try{o.current.setData(p),a.current?.timeScale().fitContent(),l.current=!0}catch{}}else{const k=p[p.length-1];try{o.current.update({time:k.time,value:k.value})}catch{}}},[s,e]);const h=s.map(f=>f.open_interest).filter(f=>typeof f=="number"&&f>0),u=h[h.length-1]??0,m=h[0]??0,x=m>0?(u-m)/m*100:0,b=x>=0;return r.jsxs("div",{className:"w-full rounded-2xl bg-[#090b0e] border border-border/80 overflow-hidden shadow-xl flex flex-col",children:[r.jsxs("div",{className:"px-4 py-2 bg-bg-card/80 border-b border-border/60 flex items-center justify-between text-xs font-mono",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-accent-blue animate-pulse"}),r.jsx("span",{className:"font-semibold text-text-primary text-[11px] tracking-wide",children:"Aggregated Open Interest (USD Notional)"}),r.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-bg-elevated text-text-muted border border-border/50 uppercase",children:i.join(" + ")})]}),r.jsxs("div",{className:"flex items-center gap-3 text-[11px]",children:[r.jsx("span",{className:"text-text-muted",children:"Total OI:"}),r.jsx("span",{className:"font-bold text-accent-blue",children:ea(u)}),h.length>1&&r.jsx("span",{className:`font-semibold px-1.5 py-0.2 rounded text-[10px] ${b?"bg-emerald-500/10 text-emerald-400":"bg-rose-500/10 text-rose-400"}`,children:b?`+${x.toFixed(2)}%`:`${x.toFixed(2)}%`})]})]}),r.jsx("div",{ref:n,className:"w-full flex-1 min-h-[170px]"})]})}function Fp({symbol:s,height:e=190}){const t=y.useRef(null),i=y.useRef(null),n=y.useRef(null),{data:a}=Zt({queryKey:["fundingHistory",s],queryFn:()=>Xi.getFundingHistory(s,40),staleTime:6e4,refetchInterval:6e4});y.useEffect(()=>{if(!t.current)return;const u=xi(t.current,{width:t.current.clientWidth,height:e,layout:{background:{type:Lt.Solid,color:"#090b0e"},textColor:"#94a3b8",fontSize:10,fontFamily:"JetBrains Mono, ui-monospace, monospace"},grid:{vertLines:{color:"rgba(30, 41, 59, 0.3)",style:de.SparseDotted},horzLines:{color:"rgba(30, 41, 59, 0.3)",style:de.SparseDotted}},crosshair:{mode:Pt.Normal},rightPriceScale:{borderColor:"#1e293b",autoScale:!0},timeScale:{borderColor:"#1e293b",timeVisible:!0,secondsVisible:!1}});i.current=u;const m=u.addSeries(Er,{priceFormat:{type:"custom",formatter:f=>`${(f*100).toFixed(4)}%`}});n.current=m;const x=()=>{t.current&&i.current&&i.current.applyOptions({width:t.current.clientWidth})};window.addEventListener("resize",x);const b=new ResizeObserver(x);return b.observe(t.current),()=>{window.removeEventListener("resize",x),b.disconnect(),u.remove(),i.current=null,n.current=null}},[e]),y.useEffect(()=>{if(!n.current||!a?.history||a.history.length===0)return;const u=a.history.filter(m=>m.avg_funding!==null&&!isNaN(m.avg_funding)).map(m=>{const x=m.avg_funding;return{time:m.time,value:x,color:x>=1e-4?"rgba(239, 68, 68, 0.75)":x>=0?"rgba(16, 185, 129, 0.65)":"rgba(56, 189, 248, 0.75)"}});try{n.current.setData(u),i.current?.timeScale().fitContent()}catch{}},[a]);const o=a?.history?.[a.history.length-1],l=o?.avg_funding??0,c=l*3*365*100,d=[];o?.binance!==void 0&&o?.binance!==null&&d.push("Binance"),o?.bybit!==void 0&&o?.bybit!==null&&d.push("Bybit"),o?.okx!==void 0&&o?.okx!==null&&d.push("OKX"),o?.bitget!==void 0&&o?.bitget!==null&&d.push("Bitget");const h=d.length>0?d.join(" + "):"Binance + Bybit + OKX + Bitget";return r.jsxs("div",{className:"w-full rounded-2xl bg-[#090b0e] border border-border/80 overflow-hidden shadow-xl flex flex-col",children:[r.jsxs("div",{className:"px-4 py-2 bg-bg-card/80 border-b border-border/60 flex items-center justify-between text-xs font-mono",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-purple-400"}),r.jsx("span",{className:"font-semibold text-text-primary text-[11px] tracking-wide",children:"Multi-Exchange Funding Rate History (8h Interval)"}),r.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-bg-elevated text-text-muted border border-border/50 uppercase",children:h})]}),r.jsxs("div",{className:"flex items-center gap-3 text-[11px]",children:[r.jsx("span",{className:"text-text-muted",children:"Current Rate:"}),r.jsxs("span",{className:`font-bold ${l>0?"text-emerald-400":l<0?"text-sky-400":"text-text-primary"}`,children:[(l*100).toFixed(4),"%"]}),r.jsxs("span",{className:"text-text-muted text-[10px]",children:["(APR: ",c>0?`+${c.toFixed(1)}%`:`${c.toFixed(1)}%`,")"]})]})]}),r.jsx("div",{ref:t,className:"w-full flex-1 min-h-[170px]"})]})}function Up({data:s,symbol:e,isWsConnected:t}){const i=s?.exchanges,n=s?.ref_price||0,a=d=>d==null||d===0?"-":d>=1e3?`$${d.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`:d>=1?`$${d.toFixed(4)}`:`$${d.toFixed(6)}`,o=d=>{if(d==null)return"-";const h=d*100,u=h<0;return r.jsx("span",{className:u?"text-emerald-400 font-semibold":Math.abs(h)>.03?"text-amber-400 font-semibold":"text-text-secondary",children:h>0?`+${h.toFixed(4)}%`:`${h.toFixed(4)}%`})},l=d=>d==null||d===0?"-":d>=1e9?`$${(d/1e9).toFixed(2)}B`:d>=1e6?`$${(d/1e6).toFixed(2)}M`:d>=1e3?`$${(d/1e3).toFixed(1)}K`:`$${d.toLocaleString()}`,c=[{id:"binance",name:"Binance USDⓈ-M",tag:"CEX Lead",info:i?.binance},{id:"bybit",name:"Bybit Linear",tag:"CEX Direct",info:i?.bybit},{id:"okx",name:"OKX Swap",tag:"CEX Global",info:i?.okx},{id:"bitget",name:"Bitget Mix",tag:"CEX Copy",info:i?.bitget},{id:"hyperliquid",name:"Hyperliquid",tag:"On-Chain DEX",info:i?.hyperliquid}];return r.jsxs("div",{className:"rounded-2xl bg-bg-card/95 border border-border/80 p-4 shadow-xl flex flex-col gap-3 font-mono",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border/60 pb-2.5",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Xs,{size:15,className:"text-accent-blue"}),r.jsxs("h3",{className:"text-xs font-bold text-text-primary tracking-wide uppercase",children:[e," Multi-Exchange Confluence"]})]}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("span",{className:`flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-semibold border ${t?"bg-emerald-500/10 text-emerald-400 border-emerald-500/30":"bg-amber-500/10 text-amber-400 border-amber-500/30"}`,children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-emerald-400 animate-pulse":"bg-amber-400"}`}),t?"Tick Stream (1.5s)":"Fast Polling"]})})]}),n>0&&r.jsxs("div",{className:"bg-bg-elevated/70 border border-border/50 rounded-xl p-2.5 flex items-center justify-between text-xs",children:[r.jsx("span",{className:"text-text-muted text-[11px]",children:"Aggregated Ref Mark Price:"}),r.jsx("span",{className:"font-bold text-text-primary text-sm tracking-wide text-sky-400",children:a(n)})]}),r.jsx("div",{className:"flex flex-col gap-2",children:c.map(d=>{const h=d.info?.available,u=d.info?.diff_pct,m=u!=null&&Math.abs(u)>=.1;return r.jsxs("div",{className:`p-2.5 rounded-xl border transition-all flex flex-col gap-1.5 ${h?"bg-bg-elevated/40 border-border/60 hover:border-accent-blue/40":"bg-bg-elevated/20 border-border/30 opacity-50"}`,children:[r.jsxs("div",{className:"flex items-center justify-between text-xs",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"font-semibold text-text-primary",children:d.name}),r.jsx("span",{className:"text-[9px] px-1.5 py-0.2 bg-bg-card border border-border rounded text-text-muted",children:d.tag})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"font-bold text-text-primary",children:a(d.info?.mark_price)}),u!=null&&r.jsx("span",{className:`text-[10px] px-1.5 py-0.2 rounded font-semibold ${m?"bg-amber-500/20 text-amber-300 border border-amber-500/40":u>0?"text-emerald-400":"text-rose-400"}`,children:u>0?`+${u}%`:`${u}%`})]})]}),h&&r.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[10px] text-text-muted pt-1 border-t border-border/30",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{children:"Funding (8h):"}),o(d.info?.funding_rate)]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{children:"Open Interest:"}),r.jsx("span",{className:"text-text-secondary font-medium",children:l(d.info?.open_interest)})]})]})]},d.id)})})]})}const qp=[{id:"1m",label:"1m"},{id:"5m",label:"5m"},{id:"15m",label:"15m"},{id:"1h",label:"1H"},{id:"4h",label:"4H"},{id:"1d",label:"1D"}],Wp=[{id:"auto",label:"⚡ Aggregated (All)"},{id:"binance",label:"Binance"},{id:"bybit",label:"Bybit"},{id:"okx",label:"OKX"},{id:"bitget",label:"Bitget"}];function Hp({initialSymbol:s="BTCUSDT",onNavigateToAI:e}){const{data:t=[]}=us(),{data:i=[]}=li(),n=y.useMemo(()=>t.filter(A=>A.is_active),[t]),[a,o]=y.useState(()=>s&&t.some(A=>A.symbol===s)?s:n[0]?.symbol||"BTCUSDT"),[l,c]=y.useState("15m"),[d,h]=y.useState("auto"),[u,m]=y.useState(!0),[x,b]=y.useState(!0),[f,v]=y.useState(!0),[p,g]=y.useState("cvd"),[S,j]=y.useState(""),[k,C]=y.useState(!1),[M,L]=y.useState(!1),I=y.useMemo(()=>{if(!a)return;const A=a.toUpperCase().replace("/","").replace("-","");return i.find(ee=>(ee.symbol||"").toUpperCase().replace("/","").replace("-","")===A)},[i,a]),R=I?.trade_levels,E=I?.predictive?.liquidation_magnets,{candles:F,currentPrice:B,multiStream:z,isAggregated:V,exchangesIncluded:q,isLoading:J,isWsConnected:oe,refetchCandles:$}=tu({symbol:a,timeframe:l,exchange:d,enabled:!0}),W=y.useMemo(()=>S.trim()?n.filter(A=>A.symbol.toLowerCase().includes(S.toLowerCase())||A.display_name.toLowerCase().includes(S.toLowerCase())):n,[n,S]),N=A=>A==null||A===0||isNaN(A)?"":A>=1e3?`$${A.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`:A>=1?`$${A.toFixed(4)}`:A>=.01?`$${A.toFixed(6)}`:`$${A.toFixed(8)}`,U=y.useMemo(()=>!I||I.symbol!==a?{showLevels:u,showMagnets:x}:{entryPrice:R?.entry_price,stopLoss:R?.stop_loss,takeProfit1:R?.take_profit_1,takeProfit2:R?.take_profit_2,upperMagnet:E?.upper_magnet,lowerMagnet:E?.lower_magnet,showLevels:u,showMagnets:x},[I,a,R?.entry_price,R?.stop_loss,R?.take_profit_1,R?.take_profit_2,E?.upper_magnet,E?.lower_magnet,u,x]);return r.jsxs("div",{className:"flex-1 flex flex-col h-full overflow-hidden bg-bg-primary text-text-primary",children:[r.jsxs("div",{className:"px-4 py-2.5 bg-bg-card/95 border-b border-border/80 flex flex-wrap items-center justify-between gap-3 shadow-md z-20",children:[r.jsxs("div",{className:"flex items-center gap-3 relative",children:[r.jsxs("div",{className:"relative",children:[r.jsxs("button",{type:"button",onClick:()=>C(!k),className:"flex items-center gap-2 px-3 py-1.5 rounded-xl bg-bg-elevated border border-border/80 hover:border-accent-blue/50 text-xs font-mono font-bold transition-all shadow-sm active:scale-95",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-accent-blue animate-pulse"}),r.jsx("span",{className:"text-sm tracking-wide text-text-primary",children:a}),r.jsx("span",{className:"text-text-muted text-[10px]",children:"▼"})]}),k&&r.jsxs("div",{className:"absolute top-full left-0 mt-2 w-64 max-h-80 bg-bg-card border border-border/80 rounded-2xl shadow-2xl p-2 z-50 flex flex-col gap-1 backdrop-blur-xl",children:[r.jsxs("div",{className:"relative mb-1",children:[r.jsx(Zs,{size:14,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-text-muted"}),r.jsx("input",{type:"text",value:S,onChange:A=>j(A.target.value),placeholder:"Cari pair...",className:"w-full pl-8 pr-3 py-1.5 rounded-lg bg-bg-elevated text-xs font-mono border border-border/60 focus:border-accent-blue focus:outline-none",autoFocus:!0})]}),r.jsx("div",{className:"overflow-y-auto max-h-60 flex flex-col gap-0.5",children:W.map(A=>{const ee=A.symbol===a;return r.jsxs("button",{type:"button",onClick:()=>{o(A.symbol),C(!1),j("")},className:`flex items-center justify-between px-3 py-2 rounded-xl text-xs font-mono transition-all text-left ${ee?"bg-accent-blue/20 text-accent-blue font-bold border border-accent-blue/30":"hover:bg-bg-elevated text-text-secondary hover:text-text-primary"}`,children:[r.jsx("span",{children:A.display_name||A.symbol}),A.streak_count&&A.streak_count>1?r.jsxs("span",{className:"text-[10px] px-1.5 py-0.2 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30",children:[A.streak_count,"🔥"]}):null]},A.symbol)})})]})]}),r.jsxs("div",{className:"flex items-center gap-2 font-mono",children:[r.jsx("span",{className:"text-base sm:text-lg font-extrabold text-sky-400 tracking-tight",children:N(B)||"-"}),I&&r.jsx(dr,{direction:I.direction,size:"sm"})]})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("div",{className:"flex items-center bg-bg-elevated p-1 rounded-xl border border-border/70 shadow-inner",children:qp.map(A=>r.jsx("button",{type:"button",onClick:()=>c(A.id),className:`px-2.5 py-1 rounded-lg text-xs font-mono font-medium transition-all ${l===A.id?"bg-accent-blue text-white shadow-sm font-bold":"text-text-secondary hover:text-text-primary"}`,children:A.label},A.id))}),r.jsx("div",{className:"hidden sm:flex items-center bg-bg-elevated p-1 rounded-xl border border-border/70 shadow-inner",children:Wp.map(A=>r.jsx("button",{type:"button",onClick:()=>h(A.id),className:`px-2 py-1 rounded-lg text-[11px] font-mono transition-all ${d===A.id?"bg-bg-card text-accent-blue font-bold border border-accent-blue/30 shadow-sm":"text-text-muted hover:text-text-secondary"}`,children:A.label},A.id))})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("button",{type:"button",onClick:()=>m(!u),title:"Toggle Trade Plan Levels (Entry, SL, TP)",className:`px-2.5 py-1.5 rounded-xl border text-xs font-mono flex items-center gap-1.5 transition-all active:scale-95 ${u?"bg-sky-500/15 border-sky-500/40 text-sky-300 font-semibold":"bg-bg-elevated border-border text-text-muted hover:text-text-secondary"}`,children:[u?r.jsx(Go,{size:13}):r.jsx(Qo,{size:13}),r.jsx("span",{className:"hidden md:inline",children:"Levels"})]}),r.jsxs("button",{type:"button",onClick:()=>b(!x),title:"Toggle Liquidation Magnet Pools",className:`px-2.5 py-1.5 rounded-xl border text-xs font-mono flex items-center gap-1.5 transition-all active:scale-95 ${x?"bg-purple-500/15 border-purple-500/40 text-purple-300 font-semibold":"bg-bg-elevated border-border text-text-muted hover:text-text-secondary"}`,children:[r.jsx(lr,{size:13}),r.jsx("span",{className:"hidden md:inline",children:"Magnets"})]}),r.jsxs("button",{type:"button",onClick:()=>v(!f),title:"Toggle Sub-Chart Analytics (CVD, Aggregated OI, Funding History)",className:`px-2.5 py-1.5 rounded-xl border text-xs font-mono flex items-center gap-1.5 transition-all active:scale-95 ${f?"bg-amber-500/15 border-amber-500/40 text-amber-300 font-semibold":"bg-bg-elevated border-border text-text-muted hover:text-text-secondary"}`,children:[r.jsx(nt,{size:13}),r.jsx("span",{className:"hidden md:inline",children:"Analytics"})]}),r.jsx("button",{type:"button",onClick:()=>$(),title:"Refresh Data Chart",className:"p-1.5 rounded-xl bg-bg-elevated border border-border hover:border-accent-blue text-text-secondary hover:text-text-primary transition-all active:scale-95",children:r.jsx(Re,{size:14,className:J?"animate-spin text-accent-blue":""})}),e&&r.jsxs("button",{type:"button",onClick:()=>e(a),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-purple-600/20 hover:bg-purple-600/30 text-purple-300 border border-purple-500/40 text-xs font-mono font-semibold transition-all active:scale-95",children:[r.jsx(Be,{size:13}),r.jsx("span",{className:"hidden lg:inline",children:"Tanya Damian"})]}),r.jsxs("button",{type:"button",onClick:()=>L(!0),className:"flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-400 hover:to-amber-500 text-black font-bold text-xs font-mono shadow-md shadow-amber-500/20 transition-all active:scale-95",children:[r.jsx(Ae,{size:14,className:"fill-black"}),r.jsx("span",{children:"Eksekusi"})]})]})]}),r.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row overflow-hidden relative",children:[r.jsxs("div",{className:"flex-1 flex flex-col p-3 overflow-y-auto gap-3",children:[r.jsx("div",{className:"flex-1 min-h-[400px] flex flex-col",children:r.jsx(Ip,{candles:F,symbol:a,overlays:U,height:f?400:580,isLoading:J})}),f&&r.jsxs("div",{className:"flex flex-col gap-2 shrink-0",children:[r.jsxs("div",{className:"flex items-center justify-between px-1",children:[r.jsxs("div",{className:"flex items-center gap-1 bg-bg-card p-1 rounded-xl border border-border/80 shadow-inner",children:[r.jsxs("button",{type:"button",onClick:()=>g("cvd"),className:`flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-mono font-semibold transition-all ${p==="cvd"?"bg-amber-500/15 text-amber-300 border border-amber-500/40 shadow-sm":"text-text-muted hover:text-text-secondary"}`,children:[r.jsx(nt,{size:12}),r.jsx("span",{children:"Aggregated CVD"})]}),r.jsxs("button",{type:"button",onClick:()=>g("oi"),className:`flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-mono font-semibold transition-all ${p==="oi"?"bg-sky-500/15 text-sky-300 border border-sky-500/40 shadow-sm":"text-text-muted hover:text-text-secondary"}`,children:[r.jsx(Qe,{size:12}),r.jsx("span",{children:"Aggregated OI ($)"})]}),r.jsxs("button",{type:"button",onClick:()=>g("funding"),className:`flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-mono font-semibold transition-all ${p==="funding"?"bg-purple-500/15 text-purple-300 border border-purple-500/40 shadow-sm":"text-text-muted hover:text-text-secondary"}`,children:[r.jsx(Yo,{size:12}),r.jsx("span",{children:"Funding History"})]})]}),V&&r.jsxs("div",{className:"hidden sm:flex items-center gap-1.5 text-[10px] font-mono text-text-muted px-2.5 py-1 rounded-xl bg-bg-card border border-border/70",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"}),r.jsxs("span",{children:["Aggregated: ",q.join(" + ").toUpperCase()]})]})]}),r.jsxs("div",{className:"h-[185px]",children:[p==="cvd"&&r.jsx(Dp,{candles:F,symbol:a,height:185}),p==="oi"&&r.jsx(Bp,{candles:F,symbol:a,height:185,exchangesIncluded:q}),p==="funding"&&r.jsx(Fp,{symbol:a,height:185})]})]})]}),r.jsxs("div",{className:"w-full lg:w-80 xl:w-96 border-t lg:border-t-0 lg:border-l border-border/80 bg-bg-card/70 p-3 overflow-y-auto flex flex-col gap-3 font-mono text-xs",children:[r.jsxs("div",{className:"p-3.5 rounded-2xl bg-bg-elevated/80 border border-border/80 flex flex-col gap-2.5 shadow-lg",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border/60 pb-2",children:[r.jsxs("span",{className:"font-bold text-text-primary text-[11px] uppercase tracking-wide flex items-center gap-1.5",children:[r.jsx(Jo,{size:13,className:"text-accent-blue"}),"Signal Trade Levels"]}),R?.risk_reward&&r.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-accent-blue/15 text-accent-blue border border-accent-blue/30 font-bold",children:["R:R ",R.risk_reward]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[11px]",children:[r.jsxs("div",{className:"p-2 rounded-xl bg-bg-card border border-sky-500/20 flex flex-col",children:[r.jsx("span",{className:"text-[10px] text-text-muted",children:"Entry Zone:"}),r.jsx("span",{className:"font-bold text-sky-400",children:R?.entry_zone||N(R?.entry_price)||"-"})]}),r.jsxs("div",{className:"p-2 rounded-xl bg-bg-card border border-rose-500/20 flex flex-col",children:[r.jsx("span",{className:"text-[10px] text-text-muted",children:"Stop Loss:"}),r.jsx("span",{className:"font-bold text-rose-400",children:R?.stop_loss_str||N(R?.stop_loss)||"-"})]}),r.jsxs("div",{className:"p-2 rounded-xl bg-bg-card border border-emerald-500/20 flex flex-col",children:[r.jsx("span",{className:"text-[10px] text-text-muted",children:"Take Profit 1:"}),r.jsx("span",{className:"font-bold text-emerald-400",children:R?.take_profit_1_str||N(R?.take_profit_1)||"-"})]}),r.jsxs("div",{className:"p-2 rounded-xl bg-bg-card border border-emerald-500/20 flex flex-col",children:[r.jsx("span",{className:"text-[10px] text-text-muted",children:"Take Profit 2:"}),r.jsx("span",{className:"font-bold text-emerald-300",children:R?.take_profit_2_str||N(R?.take_profit_2)||"-"})]})]})]}),E&&r.jsxs("div",{className:"p-3.5 rounded-2xl bg-bg-elevated/80 border border-purple-500/30 flex flex-col gap-2.5 shadow-lg",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border/60 pb-2",children:[r.jsxs("span",{className:"font-bold text-purple-300 text-[11px] uppercase tracking-wide flex items-center gap-1.5",children:[r.jsx(ts,{size:13,className:"text-purple-400"}),"Liquidation Magnet Pools"]}),r.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-purple-500/20 text-purple-300 border border-purple-500/40 font-bold",children:["Pull: ",E.dist_upper_pct&&Math.abs(E.dist_upper_pct)<=Math.abs(E.dist_lower_pct)?"UPPER":"LOWER"]})]}),r.jsxs("div",{className:"flex flex-col gap-1.5 text-[11px]",children:[r.jsxs("div",{className:"flex items-center justify-between p-2 rounded-xl bg-bg-card border border-border/50",children:[r.jsx("span",{className:"text-text-muted",children:"Upper Magnet (Short Liq):"}),r.jsxs("div",{className:"flex items-center gap-1.5 font-bold",children:[r.jsx("span",{className:"text-text-primary",children:E.upper_magnet_str||N(E.upper_magnet)}),r.jsxs("span",{className:"text-purple-400 text-[10px]",children:["(",E.dist_upper_pct>0?`+${E.dist_upper_pct}%`:`${E.dist_upper_pct}%`,")"]})]})]}),r.jsxs("div",{className:"flex items-center justify-between p-2 rounded-xl bg-bg-card border border-border/50",children:[r.jsx("span",{className:"text-text-muted",children:"Lower Magnet (Long Liq):"}),r.jsxs("div",{className:"flex items-center gap-1.5 font-bold",children:[r.jsx("span",{className:"text-text-primary",children:E.lower_magnet_str||N(E.lower_magnet)}),r.jsxs("span",{className:"text-purple-400 text-[10px]",children:["(",E.dist_lower_pct,"%)"]})]})]})]})]}),r.jsx(Up,{data:z,symbol:a,isWsConnected:oe})]})]}),M&&r.jsx(Ka,{isOpen:M,onClose:()=>L(!1),symbol:a,summary:{bias:I?.direction||"NEUTRAL",verdictSummary:`Setup ${I?.direction||"NEUTRAL"} untuk ${a}`,entryZone:R?.entry_zone||N(R?.entry_price)||N(B)||"",stopLoss:R?.stop_loss_str||N(R?.stop_loss)||"",takeProfit1:R?.take_profit_1_str||N(R?.take_profit_1)||"",takeProfit2:R?.take_profit_2_str||N(R?.take_profit_2)||"",takeProfitRaw:`${R?.take_profit_1_str||""} / ${R?.take_profit_2_str||""}`,leverage:"3x",riskReward:R?.risk_reward||"1:2",invalidation:"-",liquidationMagnet:E?.upper_magnet_str||"-",flowStatus:"Active"},markPrice:B})]})}function Vp(){const[s,e]=y.useState(!1),t=y.useRef(null),{data:i=[]}=us(),{data:n=[]}=li();y.useEffect(()=>{function o(l){t.current&&!t.current.contains(l.target)&&e(!1)}return s&&document.addEventListener("mousedown",o),()=>{document.removeEventListener("mousedown",o)}},[s]);const a=y.useMemo(()=>{const o=new Set(i.filter(T=>T.is_active).map(T=>T.symbol)),l=n.filter(T=>o.has(T.symbol)),c=l.length;if(c===0)return null;const d=l.filter(T=>T.direction==="LONG"),h=l.filter(T=>T.direction==="SHORT"),u=l.filter(T=>T.direction==="NEUTRAL"),m=d.length,x=h.length,b=u.length,f=Math.round(m/c*100),v=Math.round(x/c*100),p=Math.max(0,100-f-v),g=m?(d.reduce((T,E)=>T+E.conviction,0)/m).toFixed(1):"0.0",S=x?(h.reduce((T,E)=>T+E.conviction,0)/x).toFixed(1):"0.0";let j="NEUTRAL",k="Netral / Chop",C="text-text-muted",M="bg-text-muted",L="bg-bg-elevated/80",I="border-border",R="Pasar seimbang / sideways. Gunakan ukuran posisi terukur dan pasang SL ketat.";return m>=x*1.3&&f>=35?(j="BULLISH",k=f>=50?"Strong Bullish":"Bullish Bias",C="text-signal-long",M="bg-signal-long",L="bg-signal-long/10",I="border-signal-long/30",R="Pasar condong akumulasi beli. Prioritaskan setup LONG saat terjadi pullback di support."):x>=m*1.3&&v>=35&&(j="BEARISH",k=v>=50?"Strong Bearish":"Bearish Bias",C="text-signal-short",M="bg-signal-short",L="bg-signal-short/10",I="border-signal-short/30",R="Pasar condong tekanan jual. Prioritaskan setup SHORT di resistensi dan hindari kejar pucuk."),{total:c,longCount:m,shortCount:x,neutralCount:b,longPct:f,shortPct:v,neutralPct:p,avgLongConv:g,avgShortConv:S,regime:j,regimeLabel:k,textColor:C,dotColor:M,badgeBg:L,badgeBorder:I,guide:R}},[i,n]);return a?r.jsxs("div",{className:"relative shrink-0",ref:t,children:[r.jsxs("button",{type:"button",onClick:()=>e(!s),className:`flex items-center gap-1.5 sm:gap-2 px-2.5 sm:px-3 py-1 sm:py-1.5 rounded-full border text-xs font-mono transition-all shadow-sm cursor-pointer select-none active:scale-95 ${a.badgeBg} ${a.badgeBorder} hover:border-accent-blue/50`,title:`Global Market: ${a.regimeLabel} (${a.total} pair)`,children:[r.jsx("span",{className:`w-2 h-2 rounded-full ${a.dotColor} animate-pulse shrink-0`}),a.regime==="BULLISH"&&r.jsx(Qe,{size:13,className:"text-signal-long shrink-0"}),a.regime==="BEARISH"&&r.jsx(Mt,{size:13,className:"text-signal-short shrink-0"}),a.regime==="NEUTRAL"&&r.jsx(ta,{size:13,className:"text-text-muted shrink-0"}),r.jsx("span",{className:`font-bold uppercase tracking-tight text-[11px] ${a.textColor}`,children:a.regime}),r.jsxs("div",{className:"hidden lg:flex w-14 h-1.5 rounded-full bg-bg-primary overflow-hidden border border-border/40 shrink-0",children:[r.jsx("div",{style:{width:`${a.longPct}%`},className:"bg-signal-long h-full",title:`Bullish: ${a.longPct}%`}),r.jsx("div",{style:{width:`${a.neutralPct}%`},className:"bg-text-muted/30 h-full",title:`Neutral: ${a.neutralPct}%`}),r.jsx("div",{style:{width:`${a.shortPct}%`},className:"bg-signal-short h-full",title:`Bearish: ${a.shortPct}%`})]}),r.jsxs("span",{className:"hidden sm:inline text-[10px] text-text-secondary font-medium",children:[a.longCount,"L / ",a.shortCount,"S"]}),r.jsx(jt,{size:11,className:`text-text-muted transition-transform ${s?"rotate-180":""}`})]}),s&&r.jsxs("div",{className:"absolute right-0 sm:left-auto top-full mt-2 w-72 sm:w-80 rounded-xl bg-bg-card/95 backdrop-blur-md border border-border shadow-2xl p-3.5 z-50 text-xs animate-in fade-in zoom-in-95 duration-150",children:[r.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-border/60",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx(nt,{size:14,className:"text-accent-blue"}),r.jsxs("span",{className:"font-bold font-mono text-text-primary text-xs uppercase tracking-wide",children:["Global Sentiment (",a.total," Pair)"]})]}),r.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-mono font-bold uppercase border ${a.regime==="BULLISH"?"bg-signal-long/15 text-signal-long border-signal-long/30":a.regime==="BEARISH"?"bg-signal-short/15 text-signal-short border-signal-short/30":"bg-bg-elevated text-text-muted border-border"}`,children:a.regimeLabel})]}),r.jsxs("div",{className:"mt-3 space-y-2 font-mono text-[11px]",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex justify-between items-center mb-1",children:[r.jsx("span",{className:"text-signal-long font-semibold flex items-center gap-1",children:"🟢 Bullish (LONG):"}),r.jsxs("span",{className:"text-text-primary font-bold",children:[a.longCount," pair (",a.longPct,"%)"]})]}),r.jsx("div",{className:"w-full h-1.5 rounded-full bg-bg-primary overflow-hidden",children:r.jsx("div",{style:{width:`${a.longPct}%`},className:"h-full bg-signal-long rounded-full"})})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex justify-between items-center mb-1",children:[r.jsx("span",{className:"text-signal-short font-semibold flex items-center gap-1",children:"🔴 Bearish (SHORT):"}),r.jsxs("span",{className:"text-text-primary font-bold",children:[a.shortCount," pair (",a.shortPct,"%)"]})]}),r.jsx("div",{className:"w-full h-1.5 rounded-full bg-bg-primary overflow-hidden",children:r.jsx("div",{style:{width:`${a.shortPct}%`},className:"h-full bg-signal-short rounded-full"})})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex justify-between items-center mb-1",children:[r.jsx("span",{className:"text-text-muted font-medium flex items-center gap-1",children:"⚪ Netral (SIDEWAYS):"}),r.jsxs("span",{className:"text-text-secondary",children:[a.neutralCount," pair (",a.neutralPct,"%)"]})]}),r.jsx("div",{className:"w-full h-1.5 rounded-full bg-bg-primary overflow-hidden",children:r.jsx("div",{style:{width:`${a.neutralPct}%`},className:"h-full bg-text-muted/40 rounded-full"})})]})]}),r.jsxs("div",{className:"mt-3 pt-2.5 border-t border-border/40 grid grid-cols-2 gap-2 text-[10px] font-mono text-center",children:[r.jsxs("div",{className:"bg-bg-elevated/50 p-1.5 rounded-lg border border-border/40",children:[r.jsx("span",{className:"text-text-muted block text-[9px] uppercase",children:"Rerata Conv Long"}),r.jsxs("span",{className:"font-bold text-signal-long text-xs",children:[a.avgLongConv," / 10"]})]}),r.jsxs("div",{className:"bg-bg-elevated/50 p-1.5 rounded-lg border border-border/40",children:[r.jsx("span",{className:"text-text-muted block text-[9px] uppercase",children:"Rerata Conv Short"}),r.jsxs("span",{className:"font-bold text-signal-short text-xs",children:[a.avgShortConv," / 10"]})]})]}),r.jsxs("div",{className:"mt-2.5 p-2 rounded-lg bg-accent-blue/10 border border-accent-blue/20 text-[10px] flex items-start gap-1.5",children:[r.jsx(Xo,{size:12,className:"text-accent-blue shrink-0 mt-0.5"}),r.jsx("p",{className:"text-text-secondary leading-snug",children:a.guide})]})]})]}):r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-bg-elevated/60 border border-border text-[11px] font-mono text-text-muted shrink-0",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-blue animate-pulse"}),r.jsx("span",{className:"hidden sm:inline",children:"Global: Syncing..."}),r.jsx("span",{className:"sm:hidden",children:"Sync..."})]})}const Kp=y.lazy(()=>pt(()=>import("./GlobalAISettingsModal-y_W5Q-P7.js"),__vite__mapDeps([5,1,2,3])).then(s=>({default:s.GlobalAISettingsModal}))),Gp=y.lazy(()=>pt(()=>import("./ServerSettingsModal-BJC6WDDG.js"),__vite__mapDeps([6,1,2,3])).then(s=>({default:s.ServerSettingsModal})));function Qp({status:s,onClick:e}){const t={connected:{color:"text-signal-long",bg:"border-signal-long/20 bg-signal-long-bg",dot:"bg-signal-long animate-pulse",label:"Live",tooltip:Yi?"Koneksi real-time aktif (WebSocket Live)":"Koneksi real-time aktif (HTTP Fast Polling)",icon:r.jsx(el,{size:12})},connecting:{color:"text-accent-yellow",bg:"border-accent-yellow/20 bg-yellow-500/10",dot:"bg-accent-yellow animate-pulse",label:"Sync...",tooltip:"Menghubungkan ke server pasar...",icon:r.jsx(Re,{size:12,className:"animate-spin"})},disconnected:{color:"text-amber-400",bg:"border-amber-500/25 bg-amber-500/10",dot:"bg-amber-400 animate-pulse",label:"Sync",tooltip:"Koneksi terputus. Mencoba rekoneksi otomatis...",icon:r.jsx(Re,{size:12,className:"animate-spin"})},error:{color:"text-signal-short",bg:"border-signal-short/20 bg-signal-short-bg",dot:"bg-signal-short",label:"Offline",tooltip:"Koneksi ke backend server terputus",icon:r.jsx(Re,{size:12})}}[s];return r.jsxs("button",{type:"button",onClick:e,title:`${t.tooltip} (Klik untuk pengaturan server)`,className:`flex items-center gap-1.5 px-2 sm:px-3 py-1 sm:py-1.5 rounded-full border text-[11px] font-medium shrink-0 cursor-pointer hover:opacity-90 active:scale-95 transition-all ${t.bg} ${t.color}`,children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t.dot}`}),t.icon,r.jsx("span",{className:"hidden xs:inline",children:t.label})]})}function Yp(s){return s.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}function Jp({wsStatus:s,lastUpdated:e,onOpenMobileDrawer:t,onOpenAISettings:i,activePairCount:n=0,activeTab:a="signals",onTabChange:o}){const[l,c]=y.useState(!1),[d,h]=y.useState(!1),{settings:u,isConfigured:m}=ci(),x=()=>{i?i():c(!0)},b=u.provider==="vikey"?"Vikey":u.provider==="gemini"?"Gemini":u.provider==="openai"?"OpenAI":"Custom",f=u.model.includes("/")?u.model.split("/")[1]:u.model;return r.jsxs(r.Fragment,{children:[r.jsxs("header",{className:"h-14 flex items-center justify-between px-3 sm:px-5 border-b border-border bg-bg-card shrink-0 gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2 sm:gap-2.5",children:[t&&a==="signals"&&r.jsxs("button",{type:"button",onClick:t,className:"md:hidden p-2 rounded-lg bg-bg-elevated/80 border border-border text-text-secondary hover:text-text-primary hover:border-accent-blue/40 flex items-center gap-1.5 transition-all shrink-0 active:scale-95",title:"Buka Daftar Trading Pairs",children:[r.jsx(Zo,{size:16,className:"text-accent-blue"}),n>0&&r.jsx("span",{className:"text-[10px] font-mono font-bold bg-accent-blue/20 text-accent-blue px-1 rounded",children:n})]}),r.jsx("div",{className:"w-8 h-8 rounded-lg bg-accent-blue/20 border border-accent-blue/30 flex items-center justify-center shrink-0",children:r.jsx(Ae,{size:16,className:"text-accent-blue"})}),r.jsxs("div",{children:[r.jsx("h1",{className:"text-sm font-bold text-text-primary font-mono tracking-tight leading-none",children:"PerpsAI"}),r.jsx("p",{className:"text-[9px] sm:text-[10px] text-text-muted leading-none mt-0.5",children:"Signal & AI Terminal"})]})]}),o&&r.jsxs("div",{className:"hidden md:flex items-center bg-bg-elevated/90 p-1 rounded-xl border border-border shrink-0 shadow-inner",children:[r.jsxs("button",{type:"button",onClick:()=>o("signals"),className:`flex items-center gap-1.5 px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${a==="signals"?"bg-accent-blue text-white shadow-sm shadow-accent-blue/30":"text-text-secondary hover:text-text-primary"}`,children:[r.jsx(ei,{size:13}),r.jsx("span",{children:"Live Sinyal"})]}),r.jsxs("button",{type:"button",onClick:()=>o("chart"),className:`flex items-center gap-1.5 px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${a==="chart"?"bg-sky-600 text-white shadow-sm shadow-sky-600/30 font-bold":"text-text-secondary hover:text-sky-300"}`,children:[r.jsx(nt,{size:13}),r.jsx("span",{children:"Live Chart"})]}),r.jsxs("button",{type:"button",onClick:()=>o("ai"),className:`flex items-center gap-1.5 px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${a==="ai"?"bg-purple-600 text-white shadow-sm shadow-purple-600/30":"text-text-secondary hover:text-purple-300"}`,children:[r.jsx(Be,{size:13}),r.jsx("span",{children:"Damian"})]}),r.jsxs("button",{type:"button",onClick:()=>o("journal"),className:`flex items-center gap-1.5 px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${a==="journal"?"bg-emerald-600 text-white shadow-sm shadow-emerald-600/30":"text-text-secondary hover:text-emerald-300"}`,children:[r.jsx(aa,{size:13}),r.jsx("span",{children:"Jurnal Trade"})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2.5",children:[r.jsx(Vp,{}),r.jsxs("button",{type:"button",onClick:x,className:`hidden sm:flex items-center gap-1.5 sm:gap-2 px-2.5 sm:px-3 py-1 sm:py-1.5 rounded-full border text-xs transition-all shadow-sm cursor-pointer shrink-0 ${m?"bg-purple-500/10 hover:bg-purple-500/20 border-purple-500/30 hover:border-purple-400 text-purple-200":"bg-amber-500/10 hover:bg-amber-500/20 border-amber-500/30 text-amber-200 animate-pulse"}`,title:"Klik untuk konfigurasi model AI dan API Key Universal",children:[r.jsx(Be,{size:13,className:m?"text-purple-400":"text-amber-400"}),r.jsx("span",{className:"font-semibold text-[11px]",children:m?r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"text-purple-300 font-mono hidden xs:inline",children:[b,":"]})," ",r.jsx("span",{className:"text-text-primary truncate max-w-[70px] xs:max-w-[100px] sm:max-w-[120px] inline-block align-bottom font-mono",children:f})]}):r.jsx("span",{className:"font-mono",children:"Atur AI"})}),r.jsx(cr,{size:11,className:"text-text-muted hover:text-text-primary hidden sm:inline"})]}),e&&r.jsxs("div",{className:"hidden lg:flex items-center gap-1.5 text-[11px] text-text-muted",children:[r.jsx(Fs,{size:11}),r.jsx("span",{children:Yp(e)})]}),r.jsx(Qp,{status:s,onClick:()=>h(!0)})]})]}),d&&r.jsx(y.Suspense,{fallback:null,children:r.jsx(Gp,{isOpen:d,onClose:()=>h(!1)})}),!i&&l&&r.jsx(y.Suspense,{fallback:null,children:r.jsx(Kp,{isOpen:l,onClose:()=>c(!1)})})]})}function Xp({activeTab:s,onTabChange:e,onOpenMobileDrawer:t,onOpenAISettings:i,activePairCount:n,isAIConfigured:a}){return r.jsxs("nav",{className:"md:hidden fixed bottom-0 left-0 right-0 z-40 bg-bg-card/95 backdrop-blur-md border-t border-border/80 flex items-center justify-around px-1 pt-1 pb-[max(0.35rem,env(safe-area-inset-bottom))] shadow-2xl","aria-label":"Mobile Navigation",children:[r.jsxs("button",{type:"button",onClick:()=>e("signals"),className:`flex-1 flex flex-col items-center justify-center py-1 px-0.5 rounded-xl transition-all duration-150 active:scale-95 min-h-[44px] ${s==="signals"?"text-accent-blue font-semibold":"text-text-muted hover:text-text-secondary"}`,children:[r.jsxs("div",{className:"relative",children:[r.jsx(ei,{size:18,className:s==="signals"?"animate-pulse":""}),s==="signals"&&r.jsx("span",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-accent-blue"})]}),r.jsx("span",{className:"text-[10px] font-medium tracking-tight mt-0.5",children:"Sinyal"})]}),r.jsxs("button",{type:"button",onClick:()=>e("chart"),className:`flex-1 flex flex-col items-center justify-center py-1 px-0.5 rounded-xl transition-all duration-150 active:scale-95 min-h-[44px] ${s==="chart"?"text-sky-400 font-semibold":"text-text-muted hover:text-text-secondary"}`,children:[r.jsxs("div",{className:"relative",children:[r.jsx(nt,{size:18}),s==="chart"&&r.jsx("span",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-sky-400"})]}),r.jsx("span",{className:"text-[10px] font-medium tracking-tight mt-0.5",children:"Chart"})]}),r.jsxs("button",{type:"button",onClick:()=>e("ai"),className:`flex-1 flex flex-col items-center justify-center py-1 px-0.5 rounded-xl transition-all duration-150 active:scale-95 min-h-[44px] ${s==="ai"?"text-purple-400 font-semibold":"text-text-muted hover:text-text-secondary"}`,children:[r.jsxs("div",{className:"relative",children:[r.jsx(Be,{size:18}),s==="ai"&&r.jsx("span",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-purple-400"})]}),r.jsx("span",{className:"text-[10px] font-medium tracking-tight mt-0.5",children:"Damian"})]}),r.jsxs("button",{type:"button",onClick:()=>e("journal"),className:`flex-1 flex flex-col items-center justify-center py-1 px-0.5 rounded-xl transition-all duration-150 active:scale-95 min-h-[44px] ${s==="journal"?"text-emerald-400 font-semibold":"text-text-muted hover:text-text-secondary"}`,children:[r.jsxs("div",{className:"relative",children:[r.jsx(aa,{size:18}),s==="journal"&&r.jsx("span",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-emerald-400"})]}),r.jsx("span",{className:"text-[10px] font-medium tracking-tight mt-0.5",children:"Jurnal"})]}),r.jsxs("button",{type:"button",onClick:t,className:"flex-1 flex flex-col items-center justify-center py-1 px-0.5 rounded-xl text-text-muted hover:text-text-primary transition-all duration-150 active:scale-95 min-h-[44px]",children:[r.jsxs("div",{className:"relative",children:[r.jsx(Xs,{size:18}),n>0&&r.jsx("span",{className:"absolute -top-1 -right-2 px-1 py-0.2 bg-accent-blue/20 text-accent-blue border border-accent-blue/40 text-[9px] font-mono font-bold rounded-full leading-none",children:n})]}),r.jsx("span",{className:"text-[10px] font-medium tracking-tight mt-0.5",children:"Pairs"})]}),r.jsxs("button",{type:"button",onClick:i,className:"flex-1 flex flex-col items-center justify-center py-1 px-0.5 rounded-xl text-text-muted hover:text-text-primary transition-all duration-150 active:scale-95 min-h-[44px]",children:[r.jsxs("div",{className:"relative",children:[a?r.jsx(Fe,{size:18,className:"text-purple-400"}):r.jsx(cr,{size:18,className:"text-amber-400 animate-pulse"}),r.jsx("span",{className:`absolute -top-0.5 -right-1 w-1.5 h-1.5 rounded-full ${a?"bg-signal-long":"bg-amber-400 animate-ping"}`})]}),r.jsx("span",{className:"text-[10px] font-medium tracking-tight mt-0.5",children:"Atur AI"})]})]})}const Zp=3e4,ef=1e3;function tf(){const[s,e]=y.useState(()=>Vt()?"connecting":"connected"),[t,i]=y.useState(()=>Vt()?null:new Date),n=y.useRef(null),a=y.useRef(0),o=y.useRef(null),l=y.useRef(!0),c=y.useRef(0),d=os(),h=y.useRef(null),u=y.useCallback(()=>{if(!l.current)return;const b=Vt();if(!b){e("connected"),i(new Date);return}try{e("connecting");const f=new WebSocket(b);n.current=f,f.onopen=()=>{l.current&&(e("connected"),a.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{f.readyState===WebSocket.OPEN&&f.send(JSON.stringify({type:"ping"}))},2e4))},f.onmessage=v=>{if(l.current)try{const p=JSON.parse(v.data);if(p.type==="signal_update"&&p.data){const g=p.data,S=Date.now();S-c.current>3e3&&(c.current=S,i(new Date)),d.setQueryData(ct,j=>{if(!j)return[g];const k=j.findIndex(M=>M.symbol===g.symbol);if(k===-1)return[...j,g];const C=[...j];return C[k]=g,C}),d.setQueryData([...ct,g.symbol],g)}if((p.type==="pair_updated"||p.type==="pair_update")&&p.data){const g=p.data;d.setQueryData(ai,S=>S?S.map(j=>j.symbol===g.symbol?{...j,...g}:j):[g])}(p.type==="journal_updated"||p.type==="journal_update")&&p.data&&window.dispatchEvent(new CustomEvent("journal-updated",{detail:p.data}))}catch{}},f.onclose=()=>{h.current&&clearInterval(h.current),l.current&&(e("disconnected"),m())},f.onerror=()=>{h.current&&clearInterval(h.current),l.current&&(e("error"),f.close())}}catch{h.current&&clearInterval(h.current),e("error"),m()}},[d]),m=y.useCallback(()=>{if(!l.current||!Vt())return;const b=Math.min(ef*Math.pow(2,a.current),Zp);a.current++,o.current=setTimeout(()=>{l.current&&u()},b)},[u]);y.useEffect(()=>{l.current=!0,u();const b=()=>{n.current&&(n.current.close(),n.current=null),a.current=0,u()};return window.addEventListener("perps_server_url_changed",b),()=>{l.current=!1,window.removeEventListener("perps_server_url_changed",b),o.current&&clearTimeout(o.current),h.current&&clearInterval(h.current),n.current&&(n.current.close(),n.current=null)}},[u]);const x=y.useCallback(()=>{o.current&&clearTimeout(o.current),h.current&&clearInterval(h.current),n.current?.close(),e("disconnected")},[]);return{status:s,lastUpdated:t,disconnect:x}}const sf=y.lazy(()=>pt(()=>import("./GlobalAISettingsModal-y_W5Q-P7.js"),__vite__mapDeps([5,1,2,3])).then(s=>({default:s.GlobalAISettingsModal}))),rf=new To({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:2}}});function nf(){const[s,e]=y.useState("signals"),[t,i]=y.useState("BTCUSDT"),[n,a]=y.useState("BTCUSDT"),[o,l]=y.useState(!1),[c,d]=y.useState(!1),{status:h,lastUpdated:u}=tf(),{data:m=[]}=us(),{isConfigured:x}=ci(),b=m.filter(g=>g.is_active).length,f=y.useCallback(g=>{i(g),e("chart")},[]),v=y.useCallback(g=>{a(g),e("ai")},[]),p=y.useCallback(()=>{e(g=>g!=="signals"?"signals":g),l(!0)},[]);return r.jsxs("div",{className:"flex flex-col h-screen bg-bg-primary overflow-hidden relative",children:[r.jsx(Jp,{wsStatus:h,lastUpdated:u,activePairCount:b,activeTab:s,onTabChange:e,onOpenMobileDrawer:()=>l(!0),onOpenAISettings:()=>d(!0)}),r.jsx("div",{className:s==="signals"?"flex flex-1 overflow-hidden":"hidden",children:r.jsx(Oh,{onNavigateToAI:v,onNavigateToChart:f,isMobileDrawerOpen:o,setIsMobileDrawerOpen:l})}),r.jsx("div",{className:s==="chart"?"flex flex-1 overflow-hidden":"hidden",children:r.jsx(Hp,{initialSymbol:t,onNavigateToAI:v})}),r.jsx("div",{className:s==="ai"?"flex flex-1 overflow-hidden":"hidden",children:r.jsx(Xh,{initialSymbol:n,onSelectSymbol:a})}),r.jsx("div",{className:s==="journal"?"flex flex-1 overflow-hidden":"hidden",children:r.jsx(eu,{onNavigateToAI:v,isActiveTab:s==="journal"})}),r.jsx(Xp,{activeTab:s,onTabChange:e,onOpenMobileDrawer:p,onOpenAISettings:()=>d(!0),activePairCount:b,isAIConfigured:x}),c&&r.jsx(y.Suspense,{fallback:null,children:r.jsx(sf,{isOpen:c,onClose:()=>d(!1)})})]})}function af(){return r.jsx(Ro,{client:rf,children:r.jsx(Zd,{children:r.jsx(nf,{})})})}Hi.createRoot(document.getElementById("root")).render(r.jsx(Po.StrictMode,{children:r.jsx(af,{})}));export{Kh as A,se as B,fd as D,Ga as F,Ih as G,Is as M,$h as O,zh as V,pt as _,ft as a,Lf as b,Pf as c,xd as d,ce as e,Tf as f,ri as g,Dh as h,Rf as s,ci as u}; diff --git a/frontend/dist/index.html b/frontend/dist/index.html index 6008a50b7e54c90efc2476f9d707cd9589084ae5..bc8e43960df7870ccbc38b06d668926070f18fdd 100644 --- a/frontend/dist/index.html +++ b/frontend/dist/index.html @@ -14,11 +14,11 @@ - + - +
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 6d7ff851dd2a071e2b62e572b63d2d303dd9c7e6..539c507569fbd46266fb9169666371bc416f9318 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -78,6 +78,7 @@ function MainApp() {
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 79843e21deaab695b6f5c3cabf521acf0b101815..1fcb7c24cb84b44f6befaa7a51c7bd97bab55242 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -79,10 +79,7 @@ export const apiClient = axios.create({ }); apiClient.interceptors.request.use((reqConfig) => { - const currentBase = getServerUrl(); - if (currentBase) { - reqConfig.baseURL = currentBase; - } + reqConfig.baseURL = getServerUrl(); const token = getApiToken(); if (token) { reqConfig.headers.set('Authorization', `Bearer ${token}`); @@ -129,7 +126,7 @@ export function resolveWsUrl(): string | null { } export function resolveChartWsUrl(symbol: string): string | null { - const cleanSym = symbol.toUpperCase().replace('/', '').replace('-', ''); + const cleanSym = symbol.toUpperCase().replace(/[/-]/g, ''); if (import.meta.env.VITE_WS_URL) { return `${import.meta.env.VITE_WS_URL.replace('/ws/signals', '')}/ws/chart/${cleanSym}`; } diff --git a/frontend/src/components/chart/AggregatedOIChart.tsx b/frontend/src/components/chart/AggregatedOIChart.tsx index 3c46628c650403958f6ef79c5bb40427ba4cb667..f26b66ddbf5b876e6da8233fab22258df0f55a59 100644 --- a/frontend/src/components/chart/AggregatedOIChart.tsx +++ b/frontend/src/components/chart/AggregatedOIChart.tsx @@ -101,6 +101,8 @@ export function AggregatedOIChart({ chart.remove(); chartRef.current = null; oiSeriesRef.current = null; + isInitializedRef.current = false; + prevFirstTimeRef.current = null; }; }, [height]); @@ -117,7 +119,15 @@ export function AggregatedOIChart({ }, [symbol]); useEffect(() => { - if (!oiSeriesRef.current || !candles || candles.length === 0) { + if (!oiSeriesRef.current) { + return; + } + if (!candles || candles.length === 0) { + isInitializedRef.current = false; + prevFirstTimeRef.current = null; + try { + oiSeriesRef.current.setData([]); + } catch (e) {} return; } @@ -138,7 +148,14 @@ export function AggregatedOIChart({ value: c.open_interest as number, })); - if (oiData.length === 0) return; + if (oiData.length === 0) { + isInitializedRef.current = false; + prevFirstTimeRef.current = null; + try { + oiSeriesRef.current.setData([]); + } catch (e) {} + return; + } const firstTime = oiData[0].time; const isFirstTimeChanged = prevFirstTimeRef.current !== firstTime; @@ -165,7 +182,7 @@ export function AggregatedOIChart({ // ignore } } - }, [candles, symbol]); + }, [candles, symbol, height]); // Summary statistics const oiValues = candles diff --git a/frontend/src/components/chart/CVDVolumeChart.tsx b/frontend/src/components/chart/CVDVolumeChart.tsx index 6a439026ea468c538885e1b5d6ebb78561aed9f0..3985a13761b28fc21d152142522c2452322ef21f 100644 --- a/frontend/src/components/chart/CVDVolumeChart.tsx +++ b/frontend/src/components/chart/CVDVolumeChart.tsx @@ -111,6 +111,8 @@ export function CVDVolumeChart({ candles, symbol, height = 180 }: CVDVolumeChart chartRef.current = null; cvdSeriesRef.current = null; deltaSeriesRef.current = null; + isInitializedRef.current = false; + prevFirstTimeRef.current = null; }; }, [height]); @@ -128,7 +130,16 @@ export function CVDVolumeChart({ candles, symbol, height = 180 }: CVDVolumeChart }, [symbol]); useEffect(() => { - if (!cvdSeriesRef.current || !deltaSeriesRef.current || !candles || candles.length === 0) { + if (!cvdSeriesRef.current || !deltaSeriesRef.current) { + return; + } + if (!candles || candles.length === 0) { + isInitializedRef.current = false; + prevFirstTimeRef.current = null; + try { + cvdSeriesRef.current.setData([]); + deltaSeriesRef.current.setData([]); + } catch (e) {} return; } @@ -196,7 +207,7 @@ export function CVDVolumeChart({ candles, symbol, height = 180 }: CVDVolumeChart } } } - }, [candles, symbol]); + }, [candles, symbol, height]); const latestCvd = candles[candles.length - 1]?.cvd ?? 0; const isCvdPositive = latestCvd >= 0; diff --git a/frontend/src/components/chart/FundingRateHistoryChart.tsx b/frontend/src/components/chart/FundingRateHistoryChart.tsx index 4c7e3e08612f32e36f054c6ae06941214c8c1e87..c28d349abef6da82bbb8ce994b37f421df83fbf1 100644 --- a/frontend/src/components/chart/FundingRateHistoryChart.tsx +++ b/frontend/src/components/chart/FundingRateHistoryChart.tsx @@ -89,7 +89,13 @@ export function FundingRateHistoryChart({ symbol, height = 190 }: FundingRateHis }, [height]); useEffect(() => { - if (!seriesRef.current || !fundingData?.history || fundingData.history.length === 0) { + if (!seriesRef.current) { + return; + } + if (!fundingData?.history || fundingData.history.length === 0) { + try { + seriesRef.current.setData([]); + } catch (e) {} return; } @@ -115,7 +121,7 @@ export function FundingRateHistoryChart({ symbol, height = 190 }: FundingRateHis } catch (e) { // ignore } - }, [fundingData]); + }, [fundingData, height]); const latestHistory = fundingData?.history?.[fundingData.history.length - 1]; const latestRate = latestHistory?.avg_funding ?? 0; diff --git a/frontend/src/components/chart/MultiExchangeLiveBoard.tsx b/frontend/src/components/chart/MultiExchangeLiveBoard.tsx index 121645684de242a7041023fd7f877416fdb51981..c09fb870965f39da3109ffd259c102a4f9aea354 100644 --- a/frontend/src/components/chart/MultiExchangeLiveBoard.tsx +++ b/frontend/src/components/chart/MultiExchangeLiveBoard.tsx @@ -15,7 +15,8 @@ export function MultiExchangeLiveBoard({ data, symbol, isWsConnected }: MultiExc if (val === null || val === undefined || val === 0) return '-'; if (val >= 1000) return `$${val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; if (val >= 1) return `$${val.toFixed(4)}`; - return `$${val.toFixed(6)}`; + if (val >= 0.01) return `$${val.toFixed(6)}`; + return `$${val.toFixed(8)}`; }; const fmtFunding = (val: number | null | undefined) => { diff --git a/frontend/src/components/chart/TradingViewChart.tsx b/frontend/src/components/chart/TradingViewChart.tsx index ad1f6930f18f0297b345184e5815b874b5f70a95..98dd4db2019d709ac4387e94076def706fbd7775 100644 --- a/frontend/src/components/chart/TradingViewChart.tsx +++ b/frontend/src/components/chart/TradingViewChart.tsx @@ -220,6 +220,9 @@ export function TradingViewChart({ chartRef.current = null; candleSeriesRef.current = null; volumeSeriesRef.current = null; + priceLinesRef.current = []; + isInitializedRef.current = false; + prevFirstTimeRef.current = null; }; }, [height]); @@ -253,7 +256,16 @@ export function TradingViewChart({ // 3. Update Data when candles change (with dynamic precision + scale fitting) useEffect(() => { - if (!candleSeriesRef.current || !volumeSeriesRef.current || !candles || candles.length === 0) { + if (!candleSeriesRef.current || !volumeSeriesRef.current) { + return; + } + if (!candles || candles.length === 0) { + isInitializedRef.current = false; + prevFirstTimeRef.current = null; + try { + candleSeriesRef.current.setData([]); + volumeSeriesRef.current.setData([]); + } catch (e) {} return; } @@ -363,7 +375,7 @@ export function TradingViewChart({ } } } - }, [candles, symbol]); + }, [candles, symbol, height]); // 4. Update Price Lines (Overlays with Sanity Range Filter) useEffect(() => { @@ -487,7 +499,7 @@ export function TradingViewChart({ }); priceLinesRef.current.push(pl); } - }, [overlays, candles, symbol]); + }, [overlays, candles, symbol, height]); const latestCandle = candles && candles.length > 0 ? candles[candles.length - 1] : null; const activeStats = legendData || latestCandle; diff --git a/frontend/src/components/execution/ExecutionModal.tsx b/frontend/src/components/execution/ExecutionModal.tsx index a388dd06474d894a27ef16a19f65905467c3baf6..ca400d24923a248560b517e4819137fc40ce0ff8 100644 --- a/frontend/src/components/execution/ExecutionModal.tsx +++ b/frontend/src/components/execution/ExecutionModal.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect } from 'react'; +import { useState, useEffect, useRef } from 'react'; import { Zap, TrendingUp, @@ -44,10 +44,10 @@ function parsePrice(str?: string): number | null { } // 2. Strip known timeframe or indicator label prefixes like TP1:, TP2:, 1H, 4H, 15M, 5M, 24H, 1D const cleanedStr = str.replace(/\b(TP[12]|1[Hh]|4[Hh]|15[Mm]|5[Mm]|24[Hh]|1[Dd])\b[:\s-]*/gi, ''); - // 3. Match decimal or float number - const numMatch = cleanedStr.match(/([0-9]+(?:\.[0-9]+)?)/); + // 3. Match decimal or comma-formatted float number (e.g. 64,321.50 or 0.1850) + const numMatch = cleanedStr.match(/([0-9]+(?:,[0-9]{3})*(?:\.[0-9]+)?|[0-9]+(?:\.[0-9]+)?)/); if (numMatch && numMatch[1]) { - const val = parseFloat(numMatch[1]); + const val = parseFloat(numMatch[1].replace(/,/g, '')); if (!isNaN(val) && val > 0) return val; } return null; @@ -107,9 +107,23 @@ export function ExecutionModal({ const [isSubmitting, setIsSubmitting] = useState(false); const [authErrorMsg, setAuthErrorMsg] = useState(null); - // Sync form levels whenever symbol, summary levels, or markPrice changes + const lastSyncedSessionRef = useRef(null); + + // Sync form levels only when opening the modal or changing symbol/bias (never wipe manual edits on live markPrice ticks) useEffect(() => { + if (!isOpen) { + lastSyncedSessionRef.current = null; + return; + } + const sessionKey = `${symbol}:${isShort ? 'SHORT' : 'LONG'}`; + if (lastSyncedSessionRef.current === sessionKey) { + return; + } + const nextEntry = parsePrice(summary.entryZone) || markPrice || 0; + if (nextEntry > 0) { + lastSyncedSessionRef.current = sessionKey; + } const nextSL = parsePrice(summary.stopLoss) || (isShort ? nextEntry * 1.03 : nextEntry * 0.97); const nextTP1 = parsePrice(summary.takeProfit1) || (isShort ? nextEntry * 0.95 : nextEntry * 1.05); const nextTP2 = parsePrice(summary.takeProfit2); @@ -120,6 +134,7 @@ export function ExecutionModal({ setTakeProfit2(nextTP2); setLeverage(nextLev); }, [ + isOpen, symbol, isShort, summary.entryZone, @@ -234,14 +249,15 @@ export function ExecutionModal({ ? (isShort ? (stopLoss - refPrice) / refPrice : (refPrice - stopLoss) / refPrice) * notionalUsd : 0; - const tp1Ratio = tp1Percent / 100; - const tp2Ratio = (100 - tp1Percent) / 100; + const hasSplitTp2 = Boolean(takeProfit2 && takeProfit2 > 0 && tp1Percent < 100); + const tp1Ratio = hasSplitTp2 ? tp1Percent / 100 : 1; + const tp2Ratio = hasSplitTp2 ? (100 - tp1Percent) / 100 : 0; const estTp1Gain = refPrice > 0 && takeProfit1 > 0 ? (isShort ? (refPrice - takeProfit1) / refPrice : (takeProfit1 - refPrice) / refPrice) * (notionalUsd * tp1Ratio) : 0; - const estTp2Gain = refPrice > 0 && takeProfit2 && takeProfit2 > 0 && tp1Percent < 100 + const estTp2Gain = refPrice > 0 && hasSplitTp2 && takeProfit2 ? (isShort ? (refPrice - takeProfit2) / refPrice : (takeProfit2 - refPrice) / refPrice) * (notionalUsd * tp2Ratio) : 0; @@ -276,6 +292,11 @@ export function ExecutionModal({ return; } + if (orderType === 'Limit' && entryPrice <= 0) { + toast('Harga Entry Limit wajib lebih besar dari $0.', 'error'); + return; + } + if (stopLoss <= 0 || takeProfit1 <= 0) { toast('Stop Loss dan Target TP1 wajib diisi.', 'error'); return; @@ -358,7 +379,15 @@ export function ExecutionModal({ {defaultSide.toUpperCase()} ({summary.bias}) - Mark: ${markPrice?.toLocaleString(undefined, { minimumFractionDigits: 4 }) || 'N/A'} + Mark: {markPrice != null && markPrice > 0 + ? markPrice >= 1000 + ? `$${markPrice.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` + : markPrice >= 1 + ? `$${markPrice.toFixed(4)}` + : markPrice >= 0.01 + ? `$${markPrice.toFixed(6)}` + : `$${markPrice.toFixed(8)}` + : 'N/A'} diff --git a/frontend/src/components/layout/Header.tsx b/frontend/src/components/layout/Header.tsx index 887464aa5d53e49a3077b9fae99d49bdb589fa87..1526727862c3d38371cc3683115a7e7b9a0b377c 100644 --- a/frontend/src/components/layout/Header.tsx +++ b/frontend/src/components/layout/Header.tsx @@ -1,7 +1,7 @@ import { useState, lazy, Suspense } from 'react'; import { Zap, Wifi, RefreshCw, Clock, Bot, Settings, Menu, Activity, BookOpen, BarChart2 } from 'lucide-react'; import type { WSStatus } from '../../hooks/useWebSocket'; -import { WS_URL } from '../../api/client'; +import { resolveWsUrl } from '../../api/client'; import { useAISettings } from '../../hooks/useAISettings'; import { GlobalRegimeIndicator } from './GlobalRegimeIndicator'; @@ -33,7 +33,7 @@ function WSIndicator({ status, onClick }: { status: WSStatus; onClick?: () => vo bg: 'border-signal-long/20 bg-signal-long-bg', dot: 'bg-signal-long animate-pulse', label: 'Live', - tooltip: WS_URL ? 'Koneksi real-time aktif (WebSocket Live)' : 'Koneksi real-time aktif (HTTP Fast Polling)', + tooltip: resolveWsUrl() ? 'Koneksi real-time aktif (WebSocket Live)' : 'Koneksi real-time aktif (HTTP Fast Polling)', icon: , }, connecting: { @@ -113,6 +113,10 @@ export function Header({ ? 'Gemini' : settings.provider === 'openai' ? 'OpenAI' + : settings.provider === 'openrouter' + ? 'OpenRouter' + : settings.provider === 'groq' + ? 'Groq' : 'Custom'; const shortModel = settings.model.includes('/') diff --git a/frontend/src/components/layout/MobileDrawer.tsx b/frontend/src/components/layout/MobileDrawer.tsx index b154107e901ab1f91505b7d7ddcad30979defa01..ec9c60393af31a7b6de5d86b4c7bf097dcac665b 100644 --- a/frontend/src/components/layout/MobileDrawer.tsx +++ b/frontend/src/components/layout/MobileDrawer.tsx @@ -185,7 +185,10 @@ export function MobileDrawer({
{(['LONG', 'SHORT', 'NEUTRAL'] as const).map((dir) => { - const count = signals.filter((s) => s.direction === dir).length; + const activeSymbolSet = new Set(pairs.filter((p) => p.is_active).map((p) => p.symbol)); + const count = signals.filter( + (s) => activeSymbolSet.has(s.symbol) && s.direction === dir + ).length; return (

{(['LONG', 'SHORT', 'NEUTRAL'] as const).map((dir) => { - const count = signals.filter((s) => s.direction === dir).length; + const activeSymbolSet = new Set(pairs.filter((p) => p.is_active).map((p) => p.symbol)); + const count = signals.filter( + (s) => activeSymbolSet.has(s.symbol) && s.direction === dir + ).length; return (

{ const clean = raw.trim().toUpperCase().replace(/[\/\-_ ]/g, ''); if (!clean) return ''; - return clean.endsWith('USDT') ? clean : `${clean}USDT`; + const hasQuote = QUOTE_SUFFIXES.some((q) => clean.endsWith(q) && clean.length > q.length); + return hasQuote ? clean : `${clean}USDT`; +}; + +const formatNormalizedPair = (normalized: string): string => { + for (const q of QUOTE_SUFFIXES) { + if (normalized.endsWith(q) && normalized.length > q.length) { + return `${normalized.slice(0, -q.length)}/${q}`; + } + } + return normalized; }; export function AddPairModal({ isOpen, onClose }: AddPairModalProps) { @@ -134,7 +146,7 @@ export function AddPairModal({ isOpen, onClose }: AddPairModalProps) { {normalizeSymbol(symbol)} - ({normalizeSymbol(symbol).replace('USDT', '')}/USDT) + ({formatNormalizedPair(normalizeSymbol(symbol))})

)} diff --git a/frontend/src/components/pairs/PairItem.tsx b/frontend/src/components/pairs/PairItem.tsx index 0b3772ab54ff16f5bd267312e098fbb5e3fa888c..84782848f7959962553ba9dada8ac740e709f230 100644 --- a/frontend/src/components/pairs/PairItem.tsx +++ b/frontend/src/components/pairs/PairItem.tsx @@ -24,7 +24,7 @@ export function PairItem({ pair, signal, isSelected, onSelect }: PairItemProps) }; const streak = signal?.streak ?? pair.streak_count ?? 0; - const baseCoin = pair.symbol.replace(/(USDT|USDC|PERP)$/, ''); + const baseCoin = pair.symbol.replace(/(USDT|USDC|USD|BUSD|EUR|PERP)$/, ''); const quote = pair.symbol.slice(baseCoin.length) || 'USDT'; return ( diff --git a/frontend/src/components/signals/AIAnalysisPanel.tsx b/frontend/src/components/signals/AIAnalysisPanel.tsx index e8c561e6f2788fb90ea61a75f863f972f6525b89..5f26f81953b709b3d3a99a1f4e219cb2296cc1d3 100644 --- a/frontend/src/components/signals/AIAnalysisPanel.tsx +++ b/frontend/src/components/signals/AIAnalysisPanel.tsx @@ -16,7 +16,7 @@ import { import { Button } from '../ui/Button'; import { useToast } from '../ui/Toast'; import { aiApi } from '../../api/ai'; -import { useAISettings, VIKEY_POPULAR_MODELS, GEMINI_MODELS, OPENAI_MODELS } from '../../hooks/useAISettings'; +import { useAISettings, VIKEY_POPULAR_MODELS, GEMINI_MODELS, OPENAI_MODELS, OPENROUTER_MODELS, GROQ_MODELS } from '../../hooks/useAISettings'; import type { AIAnalysisResponse } from '../../types'; import { AIExecutiveSummaryCard } from './AIExecutiveSummaryCard'; import { FormattedMarkdown } from '../ui/FormattedMarkdown'; @@ -47,6 +47,13 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) { setSelectedModel(settings.model); }, [settings.provider, settings.model]); + // Reset analysis panel state when switching symbol to prevent stale cross-pair display + useEffect(() => { + setResult(null); + setErrorMessage(null); + setCustomQuestion(''); + }, [symbol]); + // Active model in this card (either locally overridden or universal default) const activeModel = selectedModel || settings.model; @@ -66,7 +73,7 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) { symbol, api_key: settings.api_key, provider: settings.provider, - base_url: settings.base_url, + base_url: settings.provider === 'custom' ? settings.base_url : undefined, model: activeModel, question: question || undefined, force_refresh: forceRefresh, @@ -113,6 +120,10 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) { ? 'Google Gemini' : settings.provider === 'openai' ? 'OpenAI' + : settings.provider === 'openrouter' + ? 'OpenRouter' + : settings.provider === 'groq' + ? 'Groq' : 'Custom AI'; return ( @@ -189,6 +200,28 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) { )} + ) : settings.provider === 'openrouter' ? ( + <> + {OPENROUTER_MODELS.map((m) => ( + + ))} + {!OPENROUTER_MODELS.some((m) => m.id === activeModel) && ( + + )} + + ) : settings.provider === 'groq' ? ( + <> + {GROQ_MODELS.map((m) => ( + + ))} + {!GROQ_MODELS.some((m) => m.id === activeModel) && ( + + )} + ) : ( <> {OPENAI_MODELS.map((m) => ( @@ -367,7 +400,7 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) {
MULTI-VENUE SPREAD - {result.data_snapshot.triangulation_spread_pct.toFixed(4)}% + {(result.data_snapshot.triangulation_spread_pct ?? 0).toFixed(4)}%
BINANCE FR @@ -403,11 +436,11 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) { LIQ MAGNET BAWAH {result.data_snapshot.lower_magnet}
- {result.data_snapshot.lead_lag_spread_bps !== undefined && ( + {result.data_snapshot.lead_lag_spread_bps != null && (
LEAD-LAG SPREAD - {result.data_snapshot.lead_lag_spread_bps.toFixed(1)} bps ({result.data_snapshot.leading_exchange?.toUpperCase() || 'BALANCED'}) + {(result.data_snapshot.lead_lag_spread_bps ?? 0).toFixed(1)} bps ({result.data_snapshot.leading_exchange?.toUpperCase() || 'BALANCED'})
)} @@ -419,11 +452,11 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) {
)} - {result.data_snapshot.range_24h_pct !== undefined && ( + {result.data_snapshot.range_24h_pct != null && (
RENTANG 24 JAM - {result.data_snapshot.range_24h_pct.toFixed(2)}% ({result.data_snapshot.range_position_pct?.toFixed(0)}% pos) + {(result.data_snapshot.range_24h_pct ?? 0).toFixed(2)}% ({(result.data_snapshot.range_position_pct ?? 0).toFixed(0)}% pos)
)} diff --git a/frontend/src/components/signals/AIExecutiveSummaryCard.tsx b/frontend/src/components/signals/AIExecutiveSummaryCard.tsx index 0b442e31207156818356864ae020054d1e2cd86d..70de83ac8ef732e952c8d1dea666b60bc0af8adb 100644 --- a/frontend/src/components/signals/AIExecutiveSummaryCard.tsx +++ b/frontend/src/components/signals/AIExecutiveSummaryCard.tsx @@ -124,8 +124,8 @@ export function parseAIExecutiveSummary( let tp1 = ''; let tp2 = ''; if (takeProfitRaw) { - const tp1Match = takeProfitRaw.match(/TP1\s*[:\s]*(\$?[0-9,.]+)/i); - const tp2Match = takeProfitRaw.match(/TP2\s*[:\s]*(\$?[0-9,.]+)/i); + const tp1Match = takeProfitRaw.match(/TP1[^:]*:\s*(\$?[0-9,.]+)/i); + const tp2Match = takeProfitRaw.match(/TP2[^:]*:\s*(\$?[0-9,.]+)/i); if (tp1Match) tp1 = tp1Match[1]; if (tp2Match) tp2 = tp2Match[1]; } @@ -161,8 +161,10 @@ export function parseAIExecutiveSummary( /Magnet Likuidasi[:\s*]+([^\n\r]+)/i, /Liquidation Magnet[:\s*]+([^\n\r]+)/i, ]); - if (!liquidationMagnet && fallbackSnapshot?.upper_magnet) { - liquidationMagnet = `${fallbackSnapshot.upper_magnet} / ${fallbackSnapshot.lower_magnet}`; + if (!liquidationMagnet && (fallbackSnapshot?.upper_magnet || fallbackSnapshot?.lower_magnet)) { + liquidationMagnet = [fallbackSnapshot.upper_magnet, fallbackSnapshot.lower_magnet] + .filter(Boolean) + .join(' / '); } let flowStatus = extractFromText(text, [ @@ -183,7 +185,7 @@ export function parseAIExecutiveSummary( /Disparitas Harga[:\s*]+([^\n\r]+)/i, /Lead-Lag[:\s*]+([^\n\r]+)/i, ]); - if (!leadLag && fallbackSnapshot?.lead_lag_spread_bps !== undefined) { + if (!leadLag && fallbackSnapshot?.lead_lag_spread_bps != null && Number.isFinite(fallbackSnapshot.lead_lag_spread_bps)) { leadLag = `${fallbackSnapshot.lead_lag_spread_bps.toFixed(1)} bps (${fallbackSnapshot.leading_exchange?.toUpperCase() || 'BALANCED'})`; } @@ -311,11 +313,15 @@ export function AIExecutiveSummaryCard({ const config = getBiasConfig(summary.bias); const BiasIcon = config.icon; + const formattedTpText = summary.takeProfit1 + ? (summary.takeProfit2 ? `TP1: ${summary.takeProfit1} | TP2: ${summary.takeProfit2}` : `TP1: ${summary.takeProfit1}`) + : summary.takeProfitRaw; + const handleCopySetup = () => { const textPlan = `⚡ [${symbol}] DAMIAN TRADE VERDICT: ${summary.bias} 📍 Entry: ${summary.entryZone} 🛑 Stop Loss: ${summary.stopLoss} -🎯 Target TP: ${summary.takeProfit1 ? `TP1: ${summary.takeProfit1} | TP2: ${summary.takeProfit2}` : summary.takeProfitRaw} +🎯 Target TP: ${formattedTpText} ⚖️ Risk/Reward: ${summary.riskReward} ⚡ Leverage: ${summary.leverage} ⚠️ Invalidasi: ${summary.invalidation}`; @@ -335,7 +341,7 @@ export function AIExecutiveSummaryCard({ bias: summary.bias, entry_zone: summary.entryZone, stop_loss: summary.stopLoss, - take_profit: summary.takeProfit1 ? `TP1: ${summary.takeProfit1} | TP2: ${summary.takeProfit2}` : summary.takeProfitRaw, + take_profit: formattedTpText, risk_reward: summary.riskReward, leverage: summary.leverage, invalidation: summary.invalidation, @@ -585,6 +591,7 @@ export function AIExecutiveSummaryCard({ markPrice={dataSnapshot?.mark_price} onExecutionSuccess={() => { setIsLogged(true); + window.dispatchEvent(new CustomEvent('journal-updated')); }} />
diff --git a/frontend/src/components/signals/ExchangeData.tsx b/frontend/src/components/signals/ExchangeData.tsx index 3b1296a4767b3679b627bfbec9e1ef4d1a596913..1a06d7ada980408f3b9634406bca8687b4952864 100644 --- a/frontend/src/components/signals/ExchangeData.tsx +++ b/frontend/src/components/signals/ExchangeData.tsx @@ -20,7 +20,8 @@ function formatPrice(price: number | null | undefined): string { if (price == null || isNaN(price)) return 'N/A'; if (price >= 1000) return `$${price.toLocaleString('en-US', { maximumFractionDigits: 2 })}`; if (price >= 1) return `$${price.toFixed(4)}`; - return `$${price.toFixed(6)}`; + if (price >= 0.01) return `$${price.toFixed(6)}`; + return `$${price.toFixed(8)}`; } interface ExchangeRowProps { diff --git a/frontend/src/components/signals/SignalBadge.tsx b/frontend/src/components/signals/SignalBadge.tsx index de5d4054264ba29ad5448d5be0814579c38b3737..13ad5c7545ac7e402e12deee55857819575aa674 100644 --- a/frontend/src/components/signals/SignalBadge.tsx +++ b/frontend/src/components/signals/SignalBadge.tsx @@ -34,7 +34,7 @@ const sizeClasses = { }; export function SignalBadge({ direction, size = 'md' }: SignalBadgeProps) { - const { label, icon, classes } = config[direction]; + const { label, icon, classes } = config[direction] || config.NEUTRAL; return ( String(s.oi_divergence.value || 'Neutral'), + getValue: (s) => { + const base = String(s.oi_divergence.value || 'Neutral'); + const oi4h = s.oi_divergence.oi_change_4h_pct; + if (oi4h != null && !isNaN(oi4h) && Math.abs(oi4h) >= 0.05) { + return `${base} | 4H OI: ${oi4h >= 0 ? '+' : ''}${oi4h.toFixed(2)}%`; + } + return base; + }, getScore: (s) => s.oi_divergence.score, }, { @@ -77,6 +84,13 @@ const rows: RowConfig[] = [ icon: '👥', label: 'L/S Ratio', getValue: (s) => { + const whalePos = s.ls_ratio.whale_position_long_ratio; + const retail = s.ls_ratio.retail; + const delta = s.ls_ratio.smart_money_delta; + if (whalePos != null && !isNaN(whalePos) && retail != null && !isNaN(retail)) { + const dStr = delta != null && !isNaN(delta) ? ` (Δ${delta >= 0 ? '+' : ''}${(delta * 100).toFixed(1)}%)` : ''; + return `Whale ${(whalePos * 100).toFixed(1)}%L vs Retail ${(retail * 100).toFixed(1)}%L${dStr}`; + } const top = s.ls_ratio.top_trader; if (top == null || isNaN(top)) return 'N/A'; return `${(top * 100).toFixed(1)}% Long`; @@ -88,12 +102,12 @@ const rows: RowConfig[] = [ icon: '📐', label: 'Basis', getValue: (s) => { - const b = s.basis.value; + const b = s.basis?.value; if (b == null) return 'N/A'; const num = Number(b); return !isNaN(num) ? `${num >= 0 ? '+' : ''}${num.toFixed(4)}%` : String(b); }, - getScore: (s) => s.basis.score, + getScore: (s) => s.basis?.score ?? 0, }, { key: 'market_structure', @@ -219,7 +233,7 @@ export function SignalBreakdown({ signals, predictive }: SignalBreakdownProps) {

🔮 Forward Anticipation & Liquidity Pools

- {predictive.volatility_squeeze.is_squeeze && ( + {predictive.volatility_squeeze?.is_squeeze && ( ⚡ Squeeze Active @@ -232,9 +246,11 @@ export function SignalBreakdown({ signals, predictive }: SignalBreakdownProps) { Short Liq Pool (Upper Magnet)
- {predictive.liquidation_magnets.upper_magnet_str}{' '} + {predictive.liquidation_magnets?.upper_magnet_str || '-'}{' '} - (+{predictive.liquidation_magnets.dist_upper_pct}%) + ({predictive.liquidation_magnets?.dist_upper_pct != null + ? `${predictive.liquidation_magnets.dist_upper_pct > 0 ? '+' : ''}${predictive.liquidation_magnets.dist_upper_pct}%` + : '-'})
@@ -243,9 +259,11 @@ export function SignalBreakdown({ signals, predictive }: SignalBreakdownProps) { Long Liq Pool (Lower Magnet) - {predictive.liquidation_magnets.lower_magnet_str}{' '} + {predictive.liquidation_magnets?.lower_magnet_str || '-'}{' '} - ({predictive.liquidation_magnets.dist_lower_pct}%) + ({predictive.liquidation_magnets?.dist_lower_pct != null + ? `${predictive.liquidation_magnets.dist_lower_pct}%` + : '-'}) @@ -284,7 +302,7 @@ export function SignalBreakdown({ signals, predictive }: SignalBreakdownProps) { )} {/* Fake detector warnings */} - {signals.fake_detector.is_fake && signals.fake_detector.warnings.length > 0 && ( + {signals.fake_detector?.is_fake && signals.fake_detector?.warnings?.length > 0 && (

⚠️ Fake Signal Detected

    diff --git a/frontend/src/components/signals/SignalCard.tsx b/frontend/src/components/signals/SignalCard.tsx index 75beda015428eae6e88496c30e214dfe274c2a38..6f75d778e97a602ae335c9103aaaab6017808547 100644 --- a/frontend/src/components/signals/SignalCard.tsx +++ b/frontend/src/components/signals/SignalCard.tsx @@ -22,15 +22,18 @@ interface SignalCardProps { } function formatTimeAgo(dateStr: string): string { - const now = Date.now(); + if (!dateStr) return 'just now'; const then = new Date(dateStr).getTime(); - const diffMs = now - then; - const diffSec = Math.floor(diffMs / 1000); + if (!Number.isFinite(then)) return 'just now'; + const diffMs = Date.now() - then; + const diffSec = Math.max(0, Math.floor(diffMs / 1000)); if (diffSec < 60) return `${diffSec}s ago`; const diffMin = Math.floor(diffSec / 60); if (diffMin < 60) return `${diffMin}m ago`; const diffHr = Math.floor(diffMin / 60); - return `${diffHr}h ago`; + if (diffHr < 24) return `${diffHr}h ago`; + const diffDay = Math.floor(diffHr / 24); + return `${diffDay}d ago`; } function formatUsdAmount(val: number): string { @@ -402,6 +405,78 @@ Forward Anticipation: ${signal.anticipation || levels?.anticipation || ''}`; )}
+ {/* 5-Layer Whale Movement Intelligence Strip */} + {signal.whale_flow && + ((signal.whale_flow.twap_bias && signal.whale_flow.twap_bias !== 'NEUTRAL') || + (signal.whale_flow.absorption_type && signal.whale_flow.absorption_type !== 'NONE') || + (signal.whale_flow.sweep_buy_count || 0) + (signal.whale_flow.sweep_sell_count || 0) > 0 || + (signal.whale_flow.onchain_whale_wallets || 0) > 0 || + Math.abs(signal.whale_flow.smart_money_delta || 0) >= 0.06) && ( +
+ + 🐋 Whale Radar: + {(signal.whale_flow.twap_bias === 'ACCUMULATION' || + signal.whale_flow.twap_bias === 'TWAP_BUY_ACCUMULATION' || + signal.whale_flow.twap_bias === 'WHALE_TWAP_LONG_BUILDUP') && ( + + TWAP Accum ({(signal.whale_flow.twap_buy_pct ?? 55).toFixed(0)}% Buy) + + )} + {(signal.whale_flow.twap_bias === 'DISTRIBUTION' || + signal.whale_flow.twap_bias === 'TWAP_SELL_DISTRIBUTION' || + signal.whale_flow.twap_bias === 'WHALE_TWAP_SHORT_BUILDUP') && ( + + TWAP Distrib ({(100 - (signal.whale_flow.twap_buy_pct ?? 45)).toFixed(0)}% Sell) + + )} + {(signal.whale_flow.absorption_type === 'BULLISH_ICEBERG' || + signal.whale_flow.absorption_type === 'BULLISH_ICEBERG_ABSORPTION') && ( + + 🧊 Bid Iceberg + + )} + {(signal.whale_flow.absorption_type === 'BEARISH_ICEBERG' || + signal.whale_flow.absorption_type === 'BEARISH_ICEBERG_ABSORPTION') && ( + + 🧊 Ask Iceberg + + )} + +
+ {((signal.whale_flow.sweep_buy_count || 0) + (signal.whale_flow.sweep_sell_count || 0) > 0) && ( + + Sweeps:{' '} + {signal.whale_flow.sweep_buy_count || 0}B/ + {signal.whale_flow.sweep_sell_count || 0}S + + )} + {signal.whale_flow.smart_money_delta != null && + Math.abs(signal.whale_flow.smart_money_delta) >= 0.06 && ( + 0 ? 'text-emerald-400 font-bold' : 'text-rose-400 font-bold' + } + title="Top Whale Position Ratio vs Global Retail Account Ratio" + > + SmartΔ {signal.whale_flow.smart_money_delta > 0 ? '+' : ''} + {(signal.whale_flow.smart_money_delta * 100).toFixed(0)}% + + )} + {(signal.whale_flow.onchain_whale_wallets || 0) > 0 && ( + + HL Wallets: {signal.whale_flow.onchain_whale_wallets} + + )} +
+
+ )} + {/* Dual-Horizon Selector Tabs (Intraday 15m-4H vs Swing 4H-1D) */} {signal.horizons && (
@@ -622,6 +697,9 @@ export const SignalCard = memo(SignalCardComponent, (prevProps, nextProps) => { prevProps.signal.has_spot === nextProps.signal.has_spot && prevProps.signal.predictive?.orderbook_skew?.bid_depth_usd === nextProps.signal.predictive?.orderbook_skew?.bid_depth_usd && prevProps.signal.predictive?.orderbook_skew?.ask_depth_usd === nextProps.signal.predictive?.orderbook_skew?.ask_depth_usd && + prevProps.signal.whale_flow?.flow_verdict === nextProps.signal.whale_flow?.flow_verdict && + prevProps.signal.whale_flow?.twap_bias === nextProps.signal.whale_flow?.twap_bias && + prevProps.signal.whale_flow?.absorption_type === nextProps.signal.whale_flow?.absorption_type && prevProps.onNavigateToAI === nextProps.onNavigateToAI && prevProps.onNavigateToChart === nextProps.onNavigateToChart ); diff --git a/frontend/src/components/ui/GlobalAISettingsModal.tsx b/frontend/src/components/ui/GlobalAISettingsModal.tsx index 09fd8219d9e4334b2488729ec3cc67ce45d99d15..d1773d19b8f732215402d39dfa89b30d588bc260 100644 --- a/frontend/src/components/ui/GlobalAISettingsModal.tsx +++ b/frontend/src/components/ui/GlobalAISettingsModal.tsx @@ -8,6 +8,8 @@ import { VIKEY_POPULAR_MODELS, GEMINI_MODELS, OPENAI_MODELS, + OPENROUTER_MODELS, + GROQ_MODELS, } from '../../hooks/useAISettings'; import type { AISettings } from '../../types'; @@ -40,11 +42,15 @@ export function GlobalAISettingsModal({ isOpen, onClose }: GlobalAISettingsModal const isKnownVikey = VIKEY_POPULAR_MODELS.some((m) => m.id === settings.model); const isKnownGemini = GEMINI_MODELS.some((m) => m.id === settings.model); const isKnownOpenAI = OPENAI_MODELS.some((m) => m.id === settings.model); + const isKnownOpenRouter = OPENROUTER_MODELS.some((m) => m.id === settings.model); + const isKnownGroq = GROQ_MODELS.some((m) => m.id === settings.model); if ( (settings.provider === 'vikey' && !isKnownVikey) || (settings.provider === 'gemini' && !isKnownGemini) || - (settings.provider === 'openai' && !isKnownOpenAI) + (settings.provider === 'openai' && !isKnownOpenAI) || + (settings.provider === 'openrouter' && !isKnownOpenRouter) || + (settings.provider === 'groq' && !isKnownGroq) ) { setIsCustomModelMode(true); setCustomModel(settings.model); @@ -65,6 +71,10 @@ export function GlobalAISettingsModal({ isOpen, onClose }: GlobalAISettingsModal setModel('gemini-2.5-flash'); } else if (newProvider === 'openai') { setModel('gpt-4o-mini'); + } else if (newProvider === 'openrouter') { + setModel('openai/gpt-4o-mini'); + } else if (newProvider === 'groq') { + setModel('llama-3.3-70b-versatile'); } else if (newProvider === 'custom') { setModel('anthropic/claude-fable-5'); if (!baseUrl) setBaseUrl('https://api.vikey.ai/v1'); @@ -125,7 +135,7 @@ export function GlobalAISettingsModal({ isOpen, onClose }: GlobalAISettingsModal -
+
@@ -156,8 +166,8 @@ export function GlobalAISettingsModal({ isOpen, onClose }: GlobalAISettingsModal }`} > Google Gemini - - Gemini 2.5 Flash / 1.5 Pro + + Gemini 2.5 Flash / Pro @@ -171,8 +181,38 @@ export function GlobalAISettingsModal({ isOpen, onClose }: GlobalAISettingsModal }`} > OpenAI - - Official API (gpt-4o, o3-mini) + + gpt-4o, o3-mini + + + + + + @@ -185,9 +225,9 @@ export function GlobalAISettingsModal({ isOpen, onClose }: GlobalAISettingsModal : 'bg-bg-elevated/40 border-border hover:border-border-hover text-text-secondary' }`} > - Custom Endpoint - - OpenRouter / Proxy Lain + Custom URL + + OpenAI-compatible
@@ -399,6 +439,58 @@ export function GlobalAISettingsModal({ isOpen, onClose }: GlobalAISettingsModal
)} + {provider === 'openrouter' && ( +
+ + {isCustomModelMode && ( + setCustomModel(e.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" + /> + )} +
+ )} + + {provider === 'groq' && ( +
+ + {isCustomModelMode && ( + setCustomModel(e.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" + /> + )} +
+ )} + {provider === 'custom' && ( { if (isOpen) { - setUrl(getServerUrl() || DEFAULT_CLOUD_URL); + setUrl(getServerUrl()); setApiTokenInput(getApiToken()); setShowToken(false); setTestResult(null); @@ -31,7 +31,7 @@ export function ServerSettingsModal({ isOpen, onClose }: ServerSettingsModalProp }, [isOpen]); const handleTestConnection = async (targetUrl?: string) => { - const testTarget = (targetUrl || url).trim().replace(/\/+$/, ''); + const testTarget = (targetUrl ?? url).trim().replace(/\/+$/, ''); const token = apiTokenInput.trim(); setIsTesting(true); diff --git a/frontend/src/hooks/useAISettings.ts b/frontend/src/hooks/useAISettings.ts index de5fe3a1cda3f40f9d2adeb3cfc3bbf8c1558c1b..ba31963514e3619d27fcaf328fd1cbab6a1a6d86 100644 --- a/frontend/src/hooks/useAISettings.ts +++ b/frontend/src/hooks/useAISettings.ts @@ -42,6 +42,19 @@ export const OPENAI_MODELS = [ { id: 'o3-mini', label: 'o3-mini' }, ]; +export const OPENROUTER_MODELS = [ + { id: 'openai/gpt-4o-mini', label: 'GPT-4o Mini (Recommended)' }, + { id: 'anthropic/claude-3.5-sonnet', label: 'Claude 3.5 Sonnet' }, + { id: 'deepseek/deepseek-chat', label: 'DeepSeek V3 Chat' }, + { id: 'openai/gpt-4o', label: 'GPT-4o' }, +]; + +export const GROQ_MODELS = [ + { id: 'llama-3.3-70b-versatile', label: 'Llama 3.3 70B Versatile (Recommended)' }, + { id: 'deepseek-r1-distill-llama-70b', label: 'DeepSeek R1 Distill Llama 70B' }, + { id: 'llama-3.1-8b-instant', label: 'Llama 3.1 8B Instant (Fast)' }, +]; + const SETTINGS_CHANGE_EVENT = 'perps_ai_settings_changed'; export function getStoredAISettings(): AISettings { @@ -51,6 +64,8 @@ export function getStoredAISettings(): AISettings { if (!model) { if (provider === 'vikey') model = 'anthropic/claude-fable-5'; else if (provider === 'gemini') model = 'gemini-2.5-flash'; + else if (provider === 'openrouter') model = 'openai/gpt-4o-mini'; + else if (provider === 'groq') model = 'llama-3.3-70b-versatile'; else model = 'gpt-4o-mini'; } const base_url = localStorage.getItem('perps_ai_base_url') || ''; @@ -89,8 +104,13 @@ export function useAISettings() { if (newSettings.model !== undefined) { localStorage.setItem('perps_ai_model', merged.model.trim()); } - if (newSettings.base_url !== undefined) { - localStorage.setItem('perps_ai_base_url', merged.base_url?.trim() || ''); + if ('base_url' in newSettings) { + const cleanedBaseUrl = merged.base_url?.trim() || ''; + if (cleanedBaseUrl) { + localStorage.setItem('perps_ai_base_url', cleanedBaseUrl); + } else { + localStorage.removeItem('perps_ai_base_url'); + } } if (newSettings.max_tokens !== undefined) { if (newSettings.max_tokens) { diff --git a/frontend/src/hooks/useChartData.ts b/frontend/src/hooks/useChartData.ts index 4312507bad82ebe2e0ffe2c28a143a9a0c7203f2..6eefb64e8a09cebe7b940278bc0330cfb87c6460 100644 --- a/frontend/src/hooks/useChartData.ts +++ b/frontend/src/hooks/useChartData.ts @@ -29,9 +29,12 @@ export function useChartData({ useEffect(() => { setCandles([]); setCurrentPrice(0); - setMultiStream(null); }, [symbol, timeframe, exchange]); + useEffect(() => { + setMultiStream(null); + }, [symbol]); + // 1. Initial historical candles query const { data: initialCandlesData, @@ -50,8 +53,8 @@ export function useChartData({ // Sync historical candles state with strict symbol guard useEffect(() => { if (initialCandlesData?.candles) { - const resSym = (initialCandlesData.symbol || '').toUpperCase().replace('/', '').replace('-', ''); - const curSym = (symbol || '').toUpperCase().replace('/', '').replace('-', ''); + const resSym = (initialCandlesData.symbol || '').toUpperCase().replace(/[/-]/g, ''); + const curSym = (symbol || '').toUpperCase().replace(/[/-]/g, ''); if (!resSym || resSym === curSym) { setCandles(initialCandlesData.candles); if (initialCandlesData.current_price && initialCandlesData.current_price > 0) { @@ -70,13 +73,13 @@ export function useChartData({ }); useEffect(() => { - if (multiStreamData) { + if (multiStreamData && multiStreamData.symbol === symbol) { setMultiStream(multiStreamData); if (multiStreamData.ref_price) { setCurrentPrice((prev) => (prev > 0 ? prev : (multiStreamData.ref_price || 0))); } } - }, [multiStreamData]); + }, [multiStreamData, symbol]); // 3. High-frequency WebSocket stream for real-time ticks const connectWs = useCallback(() => { @@ -86,6 +89,7 @@ export function useChartData({ try { if (wsRef.current) { + wsRef.current.onclose = null; wsRef.current.close(); } @@ -101,8 +105,8 @@ export function useChartData({ const msg = JSON.parse(event.data); if (msg.type === 'chart_tick') { // Strict symbol verification: discard any ticks from previous/mismatched symbol - const tickSym = (msg.symbol || '').toUpperCase().replace('/', '').replace('-', ''); - const curSym = (symbol || '').toUpperCase().replace('/', '').replace('-', ''); + const tickSym = (msg.symbol || '').toUpperCase().replace(/[/-]/g, ''); + const curSym = (symbol || '').toUpperCase().replace(/[/-]/g, ''); if (tickSym && curSym && tickSym !== curSym) { return; } @@ -135,6 +139,7 @@ export function useChartData({ else if (timeframe === '5m') tfSec = 300; else if (timeframe === '30m') tfSec = 1800; else if (timeframe === '1h') tfSec = 3600; + else if (timeframe === '2h') tfSec = 7200; else if (timeframe === '4h') tfSec = 14400; else if (timeframe === '1d') tfSec = 86400; @@ -157,24 +162,45 @@ export function useChartData({ volume: 0, delta: 0, cvd: (last.cvd || 0), + open_interest: last.open_interest ?? null, }; return [...prevCandles, newCandle]; } }); } - // Update multi-exchange prices if provided in tick + // Update multi-exchange prices immutably if provided in tick if (msg.exchanges) { setMultiStream((prev) => { if (!prev) return prev; - const updated = { ...prev }; - if (msg.exchanges.binance && updated.exchanges?.binance) { - updated.exchanges.binance.mark_price = msg.exchanges.binance; - } - if (msg.exchanges.bybit && updated.exchanges?.bybit) { - updated.exchanges.bybit.mark_price = msg.exchanges.bybit; - } - return updated; + const nextRef = + typeof msg.price === 'number' && Number.isFinite(msg.price) && msg.price > 0 + ? msg.price + : prev.ref_price; + const nextExchanges = { ...prev.exchanges }; + const updateVenue = (venue: 'binance' | 'bybit' | 'okx' | 'bitget') => { + const incoming = msg.exchanges?.[venue]; + if (typeof incoming === 'number' && Number.isFinite(incoming) && incoming > 0 && nextExchanges[venue]) { + nextExchanges[venue] = { + ...nextExchanges[venue], + available: true, + mark_price: incoming, + diff_pct: nextRef > 0 + ? Number((((incoming - nextRef) / nextRef) * 100).toFixed(3)) + : nextExchanges[venue].diff_pct, + }; + } + }; + updateVenue('binance'); + updateVenue('bybit'); + updateVenue('okx'); + updateVenue('bitget'); + return { + ...prev, + ref_price: nextRef, + timestamp: typeof msg.time === 'number' ? msg.time : prev.timestamp, + exchanges: nextExchanges, + }; }); } } catch (e) { @@ -204,7 +230,26 @@ export function useChartData({ useEffect(() => { isMountedRef.current = true; connectWs(); + + const handleServerUrlChange = () => { + if (reconnectTimeoutRef.current) { + clearTimeout(reconnectTimeoutRef.current); + reconnectTimeoutRef.current = null; + } + if (wsRef.current) { + wsRef.current.onclose = null; + wsRef.current.close(); + wsRef.current = null; + } + setIsWsConnected(false); + if (isMountedRef.current) { + connectWs(); + } + }; + window.addEventListener('perps_server_url_changed', handleServerUrlChange); + return () => { + window.removeEventListener('perps_server_url_changed', handleServerUrlChange); isMountedRef.current = false; if (reconnectTimeoutRef.current) { clearTimeout(reconnectTimeoutRef.current); diff --git a/frontend/src/hooks/useSignals.ts b/frontend/src/hooks/useSignals.ts index 3341a3f500408f98d9f4d54896c41ff4dab41357..611c65c4d8dd0d847a35eff6b5dbec78f7d38ae2 100644 --- a/frontend/src/hooks/useSignals.ts +++ b/frontend/src/hooks/useSignals.ts @@ -1,20 +1,21 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { signalsApi } from '../api/signals'; -import { WS_URL } from '../api/client'; +import { resolveWsUrl } from '../api/client'; import type { Signal } from '../types'; export const SIGNALS_QUERY_KEY = ['signals'] as const; export function useSignals() { + const hasWs = Boolean(resolveWsUrl()); return useQuery({ queryKey: SIGNALS_QUERY_KEY, queryFn: signalsApi.getAll, placeholderData: (previousData) => previousData, // When WebSocket is active, poll passively every 30s. If serverless without WS, poll every 6s for live updates. - refetchInterval: WS_URL ? 30000 : 6000, + refetchInterval: () => (resolveWsUrl() ? 30000 : 6000), refetchOnWindowFocus: false, // Prevent abrupt full re-renders on tab switch retry: 2, - staleTime: WS_URL ? 15000 : 4000, + staleTime: hasWs ? 15000 : 4000, }); } @@ -23,7 +24,7 @@ export function useSignal(symbol: string) { queryKey: [...SIGNALS_QUERY_KEY, symbol], queryFn: () => signalsApi.getBySymbol(symbol), placeholderData: (previousData) => previousData, - refetchInterval: WS_URL ? 30000 : 6000, + refetchInterval: () => (resolveWsUrl() ? 30000 : 6000), refetchOnWindowFocus: false, enabled: !!symbol, }); diff --git a/frontend/src/hooks/useWebSocket.ts b/frontend/src/hooks/useWebSocket.ts index bab7dc6698de56124ed03142f422b2f2c5e83b30..a85e50394db8b2bf2fb27e990cc9d9c7827a715e 100644 --- a/frontend/src/hooks/useWebSocket.ts +++ b/frontend/src/hooks/useWebSocket.ts @@ -22,9 +22,39 @@ export function useWebSocket() { const pingIntervalRef = useRef | null>(null); + const clearTimers = useCallback(() => { + if (reconnectTimer.current) { + clearTimeout(reconnectTimer.current); + reconnectTimer.current = null; + } + if (pingIntervalRef.current) { + clearInterval(pingIntervalRef.current); + pingIntervalRef.current = null; + } + }, []); + + const detachAndClose = useCallback((sock: WebSocket | null) => { + if (!sock) return; + sock.onopen = null; + sock.onmessage = null; + sock.onclose = null; + sock.onerror = null; + try { + sock.close(); + } catch { + // Ignore close errors on already-closing sockets + } + }, []); + const connect = useCallback(() => { if (!isMountedRef.current) return; + clearTimers(); + if (wsRef.current) { + detachAndClose(wsRef.current); + wsRef.current = null; + } + const currentWsUrl = resolveWsUrl(); if (!currentWsUrl) { // In serverless / HTTP mode (e.g. Vercel), mark as connected since fast HTTP polling handles live sync @@ -39,21 +69,21 @@ export function useWebSocket() { wsRef.current = ws; ws.onopen = () => { - if (!isMountedRef.current) return; + if (!isMountedRef.current || wsRef.current !== ws) return; setStatus('connected'); reconnectAttempts.current = 0; // Periodic 20s heartbeat ping to keep connection alive indefinitely if (pingIntervalRef.current) clearInterval(pingIntervalRef.current); pingIntervalRef.current = setInterval(() => { - if (ws.readyState === WebSocket.OPEN) { + if (wsRef.current === ws && ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ type: 'ping' })); } }, 20000); }; ws.onmessage = (event) => { - if (!isMountedRef.current) return; + if (!isMountedRef.current || wsRef.current !== ws) return; try { const msg: WSMessage = JSON.parse(event.data as string); @@ -96,33 +126,51 @@ export function useWebSocket() { }; ws.onclose = () => { - if (pingIntervalRef.current) clearInterval(pingIntervalRef.current); + if (wsRef.current !== ws) return; + if (pingIntervalRef.current) { + clearInterval(pingIntervalRef.current); + pingIntervalRef.current = null; + } + wsRef.current = null; if (!isMountedRef.current) return; setStatus('disconnected'); scheduleReconnect(); }; ws.onerror = () => { - if (pingIntervalRef.current) clearInterval(pingIntervalRef.current); + if (wsRef.current !== ws) return; + if (pingIntervalRef.current) { + clearInterval(pingIntervalRef.current); + pingIntervalRef.current = null; + } if (!isMountedRef.current) return; setStatus('error'); ws.close(); }; } catch { - if (pingIntervalRef.current) clearInterval(pingIntervalRef.current); + if (pingIntervalRef.current) { + clearInterval(pingIntervalRef.current); + pingIntervalRef.current = null; + } + if (!isMountedRef.current) return; setStatus('error'); scheduleReconnect(); } - }, [queryClient]); + }, [clearTimers, detachAndClose, queryClient]); const scheduleReconnect = useCallback(() => { if (!isMountedRef.current || !resolveWsUrl()) return; + if (reconnectTimer.current) { + clearTimeout(reconnectTimer.current); + reconnectTimer.current = null; + } const delay = Math.min( BASE_RECONNECT_DELAY * Math.pow(2, reconnectAttempts.current), MAX_RECONNECT_DELAY ); reconnectAttempts.current++; reconnectTimer.current = setTimeout(() => { + reconnectTimer.current = null; if (isMountedRef.current) connect(); }, delay); }, [connect]); @@ -132,8 +180,9 @@ export function useWebSocket() { connect(); const handleServerUrlChange = () => { + clearTimers(); if (wsRef.current) { - wsRef.current.close(); + detachAndClose(wsRef.current); wsRef.current = null; } reconnectAttempts.current = 0; @@ -144,21 +193,22 @@ export function useWebSocket() { return () => { isMountedRef.current = false; window.removeEventListener('perps_server_url_changed', handleServerUrlChange); - if (reconnectTimer.current) clearTimeout(reconnectTimer.current); - if (pingIntervalRef.current) clearInterval(pingIntervalRef.current); + clearTimers(); if (wsRef.current) { - wsRef.current.close(); + detachAndClose(wsRef.current); wsRef.current = null; } }; - }, [connect]); + }, [clearTimers, connect, detachAndClose]); const disconnect = useCallback(() => { - if (reconnectTimer.current) clearTimeout(reconnectTimer.current); - if (pingIntervalRef.current) clearInterval(pingIntervalRef.current); - wsRef.current?.close(); + clearTimers(); + if (wsRef.current) { + detachAndClose(wsRef.current); + wsRef.current = null; + } setStatus('disconnected'); - }, []); + }, [clearTimers, detachAndClose]); return { status, lastUpdated, disconnect }; } diff --git a/frontend/src/pages/AITerminal.tsx b/frontend/src/pages/AITerminal.tsx index a3d2eff990be0a8a717ca3b71cdb3d359a349d6b..1f4c62429c9276aaef64f4a512b4107d5fd3e408 100644 --- a/frontend/src/pages/AITerminal.tsx +++ b/frontend/src/pages/AITerminal.tsx @@ -213,7 +213,7 @@ export function AITerminal({ initialSymbol = 'BTCUSDT', onSelectSymbol }: AITerm provider: settings.provider, model: settings.model, api_key: settings.api_key, - base_url: settings.base_url, + base_url: settings.provider === 'custom' ? settings.base_url : undefined, question: questionText || undefined, force_refresh: forceRefresh, max_tokens: settings.max_tokens, @@ -584,7 +584,7 @@ export function AITerminal({ initialSymbol = 'BTCUSDT', onSelectSymbol }: AITerm return (
MULTI-VENUE SPREAD - {msg.dataSnapshot.triangulation_spread_pct.toFixed(4)}% + {(msg.dataSnapshot.triangulation_spread_pct ?? 0).toFixed(4)}%
BINANCE FR @@ -827,11 +827,11 @@ export function AITerminal({ initialSymbol = 'BTCUSDT', onSelectSymbol }: AITerm ORDERBOOK PRESSURE {msg.dataSnapshot.resting_pressure}
- {msg.dataSnapshot.lead_lag_spread_bps !== undefined && ( + {msg.dataSnapshot.lead_lag_spread_bps != null && (
LEAD-LAG SPREAD - {msg.dataSnapshot.lead_lag_spread_bps.toFixed(1)} bps ({msg.dataSnapshot.leading_exchange?.toUpperCase() || 'BALANCED'}) + {(msg.dataSnapshot.lead_lag_spread_bps ?? 0).toFixed(1)} bps ({msg.dataSnapshot.leading_exchange?.toUpperCase() || 'BALANCED'})
)} @@ -843,15 +843,15 @@ export function AITerminal({ initialSymbol = 'BTCUSDT', onSelectSymbol }: AITerm )} - {msg.dataSnapshot.range_24h_pct !== undefined && ( + {msg.dataSnapshot.range_24h_pct != null && (
24H RANGE - {msg.dataSnapshot.range_24h_pct.toFixed(2)}% ({msg.dataSnapshot.range_position_pct?.toFixed(0)}% pos) + {(msg.dataSnapshot.range_24h_pct ?? 0).toFixed(2)}% ({(msg.dataSnapshot.range_position_pct ?? 0).toFixed(0)}% pos)
)} - {msg.dataSnapshot.whale_buy_count !== undefined && ( + {msg.dataSnapshot.whale_buy_count != null && msg.dataSnapshot.whale_sell_count != null && (
WHALE BLOCKS diff --git a/frontend/src/pages/LiveChartTerminal.tsx b/frontend/src/pages/LiveChartTerminal.tsx index e599e48837e117875a0ed93d7fe4b422b0d087f2..f3e3c4fd29040fe69b35bf81fafbd3161fd59ae8 100644 --- a/frontend/src/pages/LiveChartTerminal.tsx +++ b/frontend/src/pages/LiveChartTerminal.tsx @@ -1,4 +1,4 @@ -import { useState, useMemo } from 'react'; +import { useState, useMemo, useEffect } from 'react'; import { Zap, Bot, @@ -26,6 +26,7 @@ import { ExecutionModal } from '../components/execution/ExecutionModal'; interface LiveChartTerminalProps { initialSymbol?: string; + onSelectSymbol?: (symbol: string) => void; onNavigateToAI?: (symbol: string) => void; } @@ -46,7 +47,7 @@ const EXCHANGES = [ { id: 'bitget', label: 'Bitget' }, ]; -export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }: LiveChartTerminalProps) { +export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onSelectSymbol, onNavigateToAI }: LiveChartTerminalProps) { const { data: pairs = [] } = usePairs(); const { data: signals = [] } = useSignals(); @@ -59,6 +60,12 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }: return activePairs[0]?.symbol || 'BTCUSDT'; }); + useEffect(() => { + if (initialSymbol) { + setSelectedSymbol(initialSymbol); + } + }, [initialSymbol]); + const [timeframe, setTimeframe] = useState('15m'); const [exchange, setExchange] = useState('auto'); const [showLevels, setShowLevels] = useState(true); @@ -72,9 +79,9 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }: // Active pair's signal with normalized symbol comparison const activeSignal = useMemo(() => { if (!selectedSymbol) return undefined; - const clean = selectedSymbol.toUpperCase().replace('/', '').replace('-', ''); + const clean = selectedSymbol.toUpperCase().replace(/[/-]/g, ''); return signals.find((s) => { - const sigClean = (s.symbol || '').toUpperCase().replace('/', '').replace('-', ''); + const sigClean = (s.symbol || '').toUpperCase().replace(/[/-]/g, ''); return sigClean === clean; }); }, [signals, selectedSymbol]); @@ -120,7 +127,9 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }: const overlays = useMemo(() => { // If there is no active signal or it does not match selected symbol, do not pass overlay price lines - if (!activeSignal || activeSignal.symbol !== selectedSymbol) { + const cleanActive = (activeSignal?.symbol || '').toUpperCase().replace(/[/-]/g, ''); + const cleanSelected = (selectedSymbol || '').toUpperCase().replace(/[/-]/g, ''); + if (!activeSignal || !cleanSelected || cleanActive !== cleanSelected) { return { showLevels, showMagnets }; } return { @@ -186,6 +195,7 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }: type="button" onClick={() => { setSelectedSymbol(p.symbol); + onSelectSymbol?.(p.symbol); setIsPairDropdownOpen(false); setPairSearch(''); }} @@ -490,7 +500,7 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }: Liquidation Magnet Pools - Pull: {liqMagnets.dist_upper_pct && Math.abs(liqMagnets.dist_upper_pct) <= Math.abs(liqMagnets.dist_lower_pct) ? 'UPPER' : 'LOWER'} + Pull: {liqMagnets.dist_upper_pct != null && liqMagnets.dist_lower_pct != null && Math.abs(liqMagnets.dist_upper_pct) <= Math.abs(liqMagnets.dist_lower_pct) ? 'UPPER' : 'LOWER'}
@@ -543,6 +553,7 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }: flowStatus: 'Active', }} markPrice={currentPrice} + onExecutionSuccess={() => window.dispatchEvent(new CustomEvent('journal-updated'))} /> )} diff --git a/frontend/src/pages/TradeJournal.tsx b/frontend/src/pages/TradeJournal.tsx index 190a115dfb8f3d2a4ba0a552e2abbe5e8f991b71..a8daa260fea0572e5b4f95da2a3f2af84c3c553d 100644 --- a/frontend/src/pages/TradeJournal.tsx +++ b/frontend/src/pages/TradeJournal.tsx @@ -22,7 +22,7 @@ import { Button } from '../components/ui/Button'; import { Modal } from '../components/ui/Modal'; import { useToast } from '../components/ui/Toast'; import { journalApi } from '../api/journal'; -import { useAISettings, VIKEY_POPULAR_MODELS, GEMINI_MODELS, OPENAI_MODELS } from '../hooks/useAISettings'; +import { useAISettings, VIKEY_POPULAR_MODELS, GEMINI_MODELS, OPENAI_MODELS, OPENROUTER_MODELS, GROQ_MODELS } from '../hooks/useAISettings'; import type { TradeJournalEntry, JournalStats, DamianMemory } from '../types'; import { FormattedMarkdown } from '../components/ui/FormattedMarkdown'; @@ -83,22 +83,30 @@ export function TradeJournal({ onNavigateToAI, isActiveTab }: TradeJournalProps) const { toast } = useToast(); const availableAuditModels = useMemo(() => { + let presets: { id: string; label: string }[]; switch (settings.provider) { case 'gemini': - return GEMINI_MODELS; + presets = GEMINI_MODELS; + break; case 'openai': - return OPENAI_MODELS; + presets = OPENAI_MODELS; + break; + case 'openrouter': + presets = OPENROUTER_MODELS; + break; case 'groq': - return [ - { id: 'llama-3.3-70b-versatile', label: 'Llama 3.3 70B Versatile (Recommended)' }, - { id: 'deepseek-r1-distill-llama-70b', label: 'DeepSeek R1 Distill Llama 70B' }, - { id: 'llama-3.1-8b-instant', label: 'Llama 3.1 8B Instant (Fast)' }, - ]; + presets = GROQ_MODELS; + break; case 'vikey': default: - return VIKEY_POPULAR_MODELS; + presets = VIKEY_POPULAR_MODELS; + break; } - }, [settings.provider]); + if (settings.model && !presets.some((m) => m.id === settings.model)) { + return [...presets, { id: settings.model, label: `Custom: ${settings.model}` }]; + } + return presets; + }, [settings.provider, settings.model]); // Synchronize audit model when provider or settings change useEffect(() => { @@ -185,6 +193,9 @@ export function TradeJournal({ onNavigateToAI, isActiveTab }: TradeJournalProps) const calculateHoldingDuration = (createdAtStr: string): { seconds: number; formatted: string } => { try { const created = new Date(createdAtStr).getTime(); + if (!Number.isFinite(created)) { + return { seconds: 0, formatted: 'N/A' }; + } const now = Date.now(); const diffSec = Math.max(0, Math.floor((now - created) / 1000)); const hrs = Math.floor(diffSec / 3600); @@ -303,7 +314,7 @@ export function TradeJournal({ onNavigateToAI, isActiveTab }: TradeJournalProps) api_key: settings.api_key, provider: settings.provider, model: auditModel || availableAuditModels[0]?.id, - base_url: settings.base_url, + base_url: settings.provider === 'custom' ? settings.base_url : undefined, force: true, // Allow user-triggered audit }); toast(res.message, 'success'); @@ -583,7 +594,7 @@ export function TradeJournal({ onNavigateToAI, isActiveTab }: TradeJournalProps) {!['WICK_HUNT', 'FALSE_BREAKOUT', 'BTC_DUMP', 'TREND_REVERSAL', 'PREMATURE_ENTRY', 'OTHER'].includes(item.failure_tag) && item.failure_tag} )} - {item.holding_duration_seconds && item.holding_duration_seconds > 0 && ( + {item.holding_duration_seconds != null && item.holding_duration_seconds > 0 && ( {Math.floor(item.holding_duration_seconds / 3600) > 0 @@ -591,9 +602,15 @@ export function TradeJournal({ onNavigateToAI, isActiveTab }: TradeJournalProps) : `${Math.floor(item.holding_duration_seconds / 60)}m`} )} - {item.exit_price && ( + {item.exit_price != null && item.exit_price > 0 && ( - Exit: ${item.exit_price.toLocaleString()} + Exit: ${item.exit_price >= 1000 + ? item.exit_price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + : item.exit_price >= 1 + ? item.exit_price.toFixed(4) + : item.exit_price >= 0.01 + ? item.exit_price.toFixed(6) + : item.exit_price.toFixed(8)} )} {item.audited && ( @@ -729,9 +746,9 @@ export function TradeJournal({ onNavigateToAI, isActiveTab }: TradeJournalProps)
- {item.snapshot_data.avg_fr_8h_pct !== undefined ? `${item.snapshot_data.avg_fr_8h_pct}%` : 'N/A'}{' '} + {item.snapshot_data.avg_fr_8h_pct != null ? `${Number(item.snapshot_data.avg_fr_8h_pct).toFixed(4)}%` : 'N/A'}{' '} - ({item.snapshot_data.annualized_apr_pct !== undefined ? `${item.snapshot_data.annualized_apr_pct}% APR` : ''}) + ({item.snapshot_data.annualized_apr_pct != null ? `${Number(item.snapshot_data.annualized_apr_pct).toFixed(2)}% APR` : ''})
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 75b209bfcd09df704bac7fa2093f47c98f088604..5eec78758824c49fbcb3a67d0fcd56a20991ea96 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -33,6 +33,10 @@ export interface SignalBreakdown { value: string | number; score: number; label: string; + oi_change_1h_pct?: number; + oi_change_4h_pct?: number; + intraday_score?: number; + swing_score?: number; } export interface FundingRateBreakdown extends SignalBreakdown { @@ -46,6 +50,9 @@ export interface CrossExchangeBreakdown extends SignalBreakdown { export interface LSRatioBreakdown extends SignalBreakdown { top_trader: number; retail: number; + whale_position_long_ratio?: number | null; + smart_money_delta?: number | null; + whale_sentiment?: string; } export interface MarketStructureBreakdown extends SignalBreakdown { @@ -145,8 +152,10 @@ export interface BreakoutRadar { export interface LeadLagData { max_spread_bps: number; max_spread_usd: number; - leading_venue: string; - lagging_venue: string; + max_spread_pct?: number; + leading_exchange?: string | null; + lagging_exchange?: string | null; + venue_prices?: Record; lead_lag_summary: string; } @@ -178,6 +187,36 @@ export interface WhaleFlowData { whale_sell_count: number; whale_buy_vol_usd: number; whale_sell_vol_usd: number; + sweep_buy_count?: number; + sweep_sell_count?: number; + sweep_buy_vol_usd?: number; + sweep_sell_vol_usd?: number; + twap_buy_pct?: number; + twap_bias?: + | 'ACCUMULATION' + | 'DISTRIBUTION' + | 'TWAP_BUY_ACCUMULATION' + | 'TWAP_SELL_DISTRIBUTION' + | 'WHALE_TWAP_LONG_BUILDUP' + | 'WHALE_TWAP_SHORT_BUILDUP' + | 'NEUTRAL' + | string; + absorption_type?: + | 'BULLISH_ICEBERG' + | 'BEARISH_ICEBERG' + | 'BULLISH_ICEBERG_ABSORPTION' + | 'BEARISH_ICEBERG_ABSORPTION' + | 'NONE' + | string + | null; + absorption_note?: string | null; + whale_position_long_ratio?: number | null; + retail_account_long_ratio?: number | null; + smart_money_delta?: number | null; + onchain_whale_wallets?: number; + onchain_buy_vol_usd?: number; + onchain_sell_vol_usd?: number; + whale_composite_score?: number; largest_trade_usd: number; largest_trade_side: string; flow_verdict: string; diff --git a/tests/test_audit_fixes.py b/tests/test_audit_fixes.py new file mode 100644 index 0000000000000000000000000000000000000000..11dfd29af79667893d5c3b741b38d1a183c8c7ec --- /dev/null +++ b/tests/test_audit_fixes.py @@ -0,0 +1,1646 @@ +""" +Regression tests covering bugs and miscalculations resolved in the deep audit: +1. outcome_evaluator calling ExchangeClient.get_ohlcv (instead of nonexistent fetch_ohlcv) +2. BinanceClient / BybitClient multi-horizon OI calculation & None on short/missing history +3. Whale order flow guards for contracting 15m OI and flat/doji candles +4. SignalEngine Klines Taker CVD fallback skipping partial None bars & clamping +5. Preserving explicit whale_composite_score == 0 and triggering WATCH BREAKOUT on unvetoed primed NEUTRAL +6. Decimal step rounding in BybitExecutor and taker_buy_volume clamping in market candle delta +""" + +from datetime import datetime, timedelta, timezone +import os +import sys +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +from fastapi import BackgroundTasks +import pytest + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "backend"))) + +from database.memory_store import InMemoryDatabaseStore, compute_accuracy_summary_from_rows +from engine.execution.bybit_executor import BybitExecutor +from engine.outcome_evaluator import ( + _to_epoch_ms, + async_evaluate_pending_predictions, + evaluate_prediction_against_candles, +) +from engine.signal_engine import ( + SignalEngine, + _compute_cross_exchange, + _compute_cvd, + _compute_oi_divergence, + _compute_spot_futures_cvd, + _compute_whale_order_flow, +) +from exchanges.base import BaseExchange +from exchanges.binance import TF_MAP as BINANCE_TF_MAP, BinanceClient +from exchanges.bitget import TIMEFRAME_MAP as BITGET_TF_MAP, BitgetClient +from exchanges.bybit import TF_MAP as BYBIT_TF_MAP, BybitClient +from exchanges.okx import TF_MAP as OKX_TF_MAP +from routers import ai as ai_router +from routers import signals as signals_router +from routers.market import _calculate_candle_delta + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def _make_candles(n: int = 35, price: float = 100.0, volume: float = 1000.0) -> list[dict]: + return [ + { + "timestamp": i * 900_000, + "open": price, + "high": price * 1.005, + "low": price * 0.995, + "close": price, + "volume": volume, + } + for i in range(n) + ] + + +@pytest.mark.anyio +async def test_outcome_evaluator_uses_get_ohlcv_and_bybit_fallback(): + """async_evaluate_pending_predictions must call get_ohlcv() cleanly and resolve outcomes.""" + + class BinanceOnlyGetOhlcv: + def __init__(self): + self.calls = 0 + + async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100): + self.calls += 1 + return [] # Simulate empty Binance so Bybit fallback runs + + class BybitOnlyGetOhlcv: + def __init__(self): + self.calls = 0 + + async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100): + self.calls += 1 + return [ + {"timestamp": 60_000, "open": 100.0, "high": 102.0, "low": 99.5, "close": 101.0}, + {"timestamp": 120_000, "open": 101.0, "high": 112.0, "low": 100.5, "close": 111.0}, + ] + + binance_stub = BinanceOnlyGetOhlcv() + bybit_stub = BybitOnlyGetOhlcv() + pending_rows = [ + { + "id": 42, + "symbol": "BTCUSDT", + "horizon": "intraday", + "direction": "LONG", + "entry_price": 100.0, + "stop_loss": 95.0, + "tp1": 105.0, + "tp2": 110.0, + "created_at": 1_000, + "expires_at": 500_000, + } + ] + recorded_updates = [] + + async def _fake_update(pred_id, **kwargs): + recorded_updates.append({"id": pred_id, **kwargs}) + return True + + with patch("engine.outcome_evaluator.async_get_pending_predictions", AsyncMock(return_value=pending_rows)), \ + patch("engine.outcome_evaluator.async_update_signal_prediction_outcome", side_effect=_fake_update): + res = await async_evaluate_pending_predictions(binance_stub, bybit_stub) + + assert binance_stub.calls == 1 + assert bybit_stub.calls == 1 + assert res["checked"] == 1 + assert res["resolved"] == 1 + assert len(recorded_updates) == 1 + assert recorded_updates[0]["id"] == 42 + assert recorded_updates[0]["outcome"] == "TP2" + + +def test_base_exchange_compute_oi_horizons(): + """Shared OI horizon helper must never mislabel short history as 1H or 4H.""" + assert BaseExchange._compute_oi_horizons([]) == (None, None, None) + assert BaseExchange._compute_oi_horizons([1000.0]) == (None, None, None) + + # 3 bars -> 15m only; 1h and 4h remain None + c15, c1h, c4h = BaseExchange._compute_oi_horizons([1000.0, 1020.0, 1071.0]) + assert c15 == pytest.approx(5.0) + assert c1h is None + assert c4h is None + + # 5 bars -> 15m and 1h computed; 4h remains None + series_5 = [1000.0, 1010.0, 1020.0, 1030.0, 1050.0] + c15_5, c1h_5, c4h_5 = BaseExchange._compute_oi_horizons(series_5) + assert c15_5 == pytest.approx(((1050.0 - 1030.0) / 1030.0) * 100.0, abs=1e-4) + assert c1h_5 == pytest.approx(5.0) + assert c4h_5 is None + + # 17 bars -> full 15m, 1h (-5), 4h (-17 / [0]) + series_17 = [1000.0] + [1010.0] * 11 + [1020.0, 1030.0, 1040.0, 1050.0, 1100.0] + assert len(series_17) == 17 + c15_17, c1h_17, c4h_17 = BaseExchange._compute_oi_horizons(series_17) + assert c15_17 == pytest.approx(((1100.0 - 1050.0) / 1050.0) * 100.0, abs=1e-4) + assert c1h_17 == pytest.approx(((1100.0 - 1020.0) / 1020.0) * 100.0, abs=1e-4) + assert c4h_17 == pytest.approx(10.0) + + +@pytest.mark.anyio +async def test_binance_bybit_oi_return_none_on_short_or_fallback_and_preserve_divergence(): + """Short/failed OI history returns None instead of fake 0.0 that dilutes multi-exchange divergence.""" + bnb = BinanceClient() + byb = BybitClient() + bnb._known_symbols = {"BTCUSDT"} + byb._known_symbols = {"BTCUSDT"} + + try: + # 1) Binance fallback path returns None deltas (not 0.0) + with patch.object( + bnb, + "_get", + AsyncMock(side_effect=[[{"sumOpenInterest": "5000", "sumOpenInterestValue": "500000"}]]), + ): + short_bnb = await bnb.get_open_interest("BTCUSDT") + assert short_bnb["open_interest"] == 5000.0 + assert short_bnb["oi_change_pct"] is None + assert short_bnb["oi_change_1h_pct"] is None + assert short_bnb["oi_change_4h_pct"] is None + + # 2) Bybit 3-item history (newest-first) computes 15m accurately and leaves 1h/4h None + with patch("exchanges.bybit.bulk_fetcher.get_bybit_24h_and_oi", return_value=None), \ + patch.object( + byb, + "_get", + AsyncMock(return_value={ + "list": [ + {"openInterest": "1050"}, + {"openInterest": "1000"}, + {"openInterest": "950"}, + ] + }), + ): + short_byb = await byb.get_open_interest("BTCUSDT") + assert short_byb["open_interest"] == 1050.0 + assert short_byb["oi_change_pct"] == pytest.approx(5.0) + assert short_byb["oi_change_1h_pct"] is None + assert short_byb["oi_change_4h_pct"] is None + + # 3) Unavailable OKX/Bitget OI deltas (None) must NOT dilute valid Binance +4.0% OI growth + two_bars = [{"open": 100.0, "close": 100.0}, {"open": 100.0, "close": 102.0}] + div = _compute_oi_divergence( + {"open_interest_data": {"open_interest": 1000.0, "oi_change_pct": 4.0, "oi_change_1h_pct": 6.0}, "ohlcv": {"15m": two_bars}}, + {"open_interest_data": short_bnb, "ohlcv": {"15m": two_bars}}, + None, + None, + ) + assert div["oi_change_pct"] == pytest.approx(4.0) + assert div["oi_change_1h_pct"] == pytest.approx(6.0) + finally: + await bnb.close() + await byb.close() + + +def test_whale_flow_guards_contracting_oi_and_flat_candle(): + """Active 15m OI unwinding and flat doji candles must never trigger false Iceberg Absorption.""" + flat_bar = [{"timestamp": 0, "open": 100.0, "high": 100.02, "low": 100.0, "close": 100.02, "volume": 1000.0, "taker_buy_volume": 200.0}] + healthy_bar = [{"timestamp": 0, "open": 100.0, "high": 102.0, "low": 99.0, "close": 101.9, "volume": 1000.0, "taker_buy_volume": 200.0}] + sell_trades = [{"price": 100.0, "qty": 400.0, "is_buyer_maker": True} for _ in range(3)] + + # Positive control: healthy candle + aligned positive OI expansion + sell pressure DOES trigger Iceberg Absorption + pos_res = _compute_whale_order_flow( + trades=sell_trades, + mark_price=100.0, + merged_ohlcv={"15m": healthy_bar}, + oi_signal={"oi_change_pct": 1.2, "oi_change_1h_pct": 1.5}, + ) + assert pos_res["absorption_type"] == "BULLISH_ICEBERG_ABSORPTION" + assert pos_res["whale_composite_score"] > 0 + + # Heavy sell delta on flat/doji candle even with strong OI expansion -> close_pos clamped to 0.5, no Iceberg + flat_tape_res = _compute_whale_order_flow( + trades=sell_trades, + mark_price=100.0, + merged_ohlcv={"15m": flat_bar}, + oi_signal={"oi_change_pct": 1.2, "oi_change_1h_pct": 1.5}, + ) + assert flat_tape_res["absorption_type"] is None + + flat_klines_res = _compute_whale_order_flow( + trades=[], + mark_price=100.0, + merged_ohlcv={"15m": flat_bar}, + oi_signal={"oi_change_pct": 1.2, "oi_change_1h_pct": 1.5}, + ) + assert flat_klines_res["absorption_type"] is None + + # Active 15m OI unwinding (-0.6%) must override stale positive 1h OI (+0.8%) -> no Iceberg position building + unwinding_res = _compute_whale_order_flow( + trades=sell_trades, + mark_price=100.0, + merged_ohlcv={"15m": healthy_bar}, + oi_signal={"oi_change_pct": -0.6, "oi_change_1h_pct": 0.8}, + ) + assert unwinding_res["absorption_type"] is None + + +def test_signal_engine_taker_cvd_partial_none_and_score_zero_and_watch_breakout(): + """ + 1. Klines Taker CVD fallback skips bars missing taker_buy_volume instead of counting them as 100% sell. + 2. Explicit whale_composite_score == 0 is preserved rather than overridden by raw whale volume ratio. + 3. Unvetoed breakout-primed NEUTRAL signal upgrades 'DO NOT TRADE / WAIT' -> 'WATCH BREAKOUT'. + """ + engine = SignalEngine() + + # Mix 5 valid bullish taker_buy_volume bars with 5 None bars (large volume) + mixed_15m = [ + {"timestamp": i * 900_000, "open": 100.0, "high": 101.0, "low": 99.5, "close": 100.8, "volume": 1000.0, "taker_buy_volume": 800.0} + for i in range(5) + ] + [ + {"timestamp": (5 + i) * 900_000, "open": 100.0, "high": 101.0, "low": 99.5, "close": 100.8, "volume": 5000.0, "taker_buy_volume": None} + for i in range(5) + ] + full_15m = _make_candles(25, price=100.0, volume=1000.0) + mixed_15m + flat_tf = _make_candles(35, price=100.0, volume=1000.0) + + raw = { + "symbol": "MIXUSDT", + "binance": { + "mark_price_data": {"mark_price": 100.0, "index_price": 100.0, "basis_pct": 0.0}, + "funding_rate_data": {"funding_rate": 0.0001}, + "open_interest_data": {"open_interest": 10_000_000.0, "oi_change_pct": 0.1}, + "trades": [], # Trigger Klines Taker CVD fallback + "spot_trades": [], + "ohlcv": {"1m": flat_tf, "5m": flat_tf, "15m": full_15m, "1h": flat_tf, "4h": flat_tf, "1d": flat_tf}, + "orderbook": {"bids": [[99.9, 5000]], "asks": [[100.1, 5000]]}, + }, + "bybit": None, + "okx": None, + "bitget": None, + "hyperliquid": None, + } + + res = engine.compute(raw) + assert res["confluence"]["breakdown"]["cvd"]["score"] == 1 + + # Preserve whale_composite_score == 0 + activate WATCH BREAKOUT when unvetoed NEUTRAL is primed + cancelled_whale = { + "score": 0, + "whale_composite_score": 0, + "whale_buy_vol_usd": 300_000.0, + "whale_sell_vol_usd": 100_000.0, + "whale_net_vol_usd": 200_000.0, + "whale_count": 6, + "taker_buy_pct": 52.0, + "dynamic_threshold_usd": 25_000.0, + "absorption_type": "NONE", + "absorption_score": 0, + "twap_detected": False, + "twap_direction": "NONE", + "twap_score": 0, + "block_score": 0, + "smart_money_aligned": False, + "label": "Neutral", + } + primed_radar = { + "is_breakout_primed": True, + "score": 45, + "bias": "NEUTRAL", + "radar_label": "COILED SPRING BREAKOUT", + "catalyst_summary": "BB Squeeze + OI expansion", + "catalysts": ["BB Squeeze"], + } + with patch("engine.signal_engine._compute_whale_order_flow", return_value=cancelled_whale), \ + patch("engine.signal_engine._compute_breakout_radar", return_value=primed_radar): + res_breakout = engine.compute(raw) + + assert res_breakout["confluence"]["breakdown"]["whale_order_flow"]["score"] == 0 + assert res_breakout["direction"] == "NEUTRAL" + assert res_breakout["action"] == "WATCH BREAKOUT" + + # When safety veto IS active (e.g. wide/illiquid book), WATCH BREAKOUT must NOT overwrite safety warning + raw_illiquid = { + **raw, + "binance": { + **raw["binance"], + "orderbook": {"bids": [[95.0, 100]], "asks": [[105.0, 100]]}, + }, + } + with patch("engine.signal_engine._compute_whale_order_flow", return_value=cancelled_whale), \ + patch("engine.signal_engine._compute_breakout_radar", return_value=primed_radar): + res_vetoed = engine.compute(raw_illiquid) + + assert res_vetoed["direction"] == "NEUTRAL" + assert res_vetoed["action"] != "WATCH BREAKOUT" + + +def test_bybit_decimal_round_step_and_market_delta_clamp(): + """Decimal rounding prevents IEEE 754 floor drops; market candle delta clamps oversized taker_buy_volume.""" + assert BybitExecutor._round_step(0.03, 0.01) == 0.03 + assert BybitExecutor._round_step(0.29, 0.01) == 0.29 + assert BybitExecutor._round_tick(1.005, 0.01) == 1.01 + + clamped_delta = _calculate_candle_delta({ + "open": 100.0, + "high": 102.0, + "low": 99.0, + "close": 101.0, + "volume": 100.0, + "taker_buy_volume": 125.0, + }) + assert clamped_delta == 100.0 + + +def test_memory_store_pending_reset_and_naive_timestamps_and_null_scores(): + """ + 1. Resetting journal entry to PENDING clears failure_tag, exit_price, holding_duration_seconds, audited. + 2. Naive / 'Z' ISO created_at strings work in get_recent_prediction and get_accuracy_summary. + 3. compute_accuracy_summary_from_rows tolerates None factor scores without crashing. + """ + store = InMemoryDatabaseStore() + entry = store.create_journal_entry({"symbol": "BTCUSDT", "bias": "STRONG LONG"}) + eid = entry["id"] + sl_updated = store.update_journal_status( + journal_id=eid, + status="HIT_SL", + note="Wick hunt", + failure_tag="WICK_HUNT", + exit_price=95000.0, + holding_duration_seconds=1800, + ) + assert sl_updated is not None + assert sl_updated["failure_tag"] == "WICK_HUNT" + store._journal[eid]["audited"] = True + + reset_entry = store.update_journal_status(journal_id=eid, status="PENDING", note="Reopen") + assert reset_entry is not None + assert reset_entry["status"] == "PENDING" + assert reset_entry["outcome_at"] is None + assert reset_entry["failure_tag"] is None + assert reset_entry["exit_price"] is None + assert reset_entry["holding_duration_seconds"] is None + assert reset_entry["audited"] is False + + # Naive UTC timestamp (without tzinfo) for evaluated prediction + naive_recent = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + pred = store.insert_signal_prediction({ + "symbol": "ETHUSDT", + "horizon": "intraday", + "direction": "LONG", + "conviction": 7, + "regime": "trending", + "sniper_grade": "SNIPER_A_PLUS", + "entry_price": 2000.0, + "stop_loss": 1950.0, + "tp1": 2100.0, + "tp2": 2200.0, + "factor_scores": {"whale_order_flow": {"score": None}, "cvd": None, "ls_ratio": "1"}, + "created_at": naive_recent, + }) + store.update_signal_prediction_outcome(pred["id"], outcome="TP1_OPEN", outcome_price=2100.0, r_multiple=2.0) + + recent_hit = store.get_recent_prediction("ETHUSDT", "intraday", "LONG", cooldown_hours=4) + assert recent_hit is not None + assert recent_hit["id"] == pred["id"] + + acc = store.get_accuracy_summary(days=30, symbol="ETHUSDT") + assert acc["total_evaluated"] == 1 + assert "ls_ratio" in acc["by_factor"] + + direct_acc = compute_accuracy_summary_from_rows([ + { + "direction": "SHORT", + "horizon": "swing", + "sniper_grade": "STANDARD", + "outcome": "SL", + "r_multiple": -1.0, + "factor_scores": {"whale_order_flow": {"score": None}, "funding_rate": {"score": -2}}, + } + ]) + assert direct_acc["total_evaluated"] == 1 + assert direct_acc["by_factor"]["funding_rate"]["aligned_trades"] == 1 + assert "whale_order_flow" not in direct_acc["by_factor"] + + +@pytest.mark.anyio +async def test_exchange_timeframes_and_bitget_oi_null_mark_and_trade_sort(): + """Verify 3m/30m/2h mappings, Bitget None OI USD guard when mark_price is None, and ascending trade sort.""" + for tf in ("3m", "30m", "2h"): + assert tf in BYBIT_TF_MAP + assert tf in OKX_TF_MAP + assert tf in BITGET_TF_MAP + + bg = BitgetClient() + try: + # 1) Empty OI payload includes oi_change_pct: None + with patch.object(bg, "_get", AsyncMock(return_value={})): + empty_oi = await bg.get_open_interest("BTCUSDT") + assert empty_oi == {"open_interest": None, "open_interest_value": None, "oi_change_pct": None} + + # 2) Valid size but missing mark_price yields open_interest_value: None (never size * 1.0) + with patch.object(bg, "_get", AsyncMock(return_value={"openInterestList": [{"size": "250.5"}]})), \ + patch.object(bg, "get_mark_price", AsyncMock(return_value={"mark_price": None})): + no_mp_oi = await bg.get_open_interest("BTCUSDT") + assert no_mp_oi["open_interest"] == 250.5 + assert no_mp_oi["open_interest_value"] is None + + # 3) Recent trades handle mixed-case side and sort ascending by time + raw_fills = [ + {"price": "101", "size": "2", "side": "Sell", "ts": "2000"}, + {"price": "100", "size": "1", "side": "BUY", "ts": "1000"}, + ] + with patch.object(bg, "_get", AsyncMock(return_value=raw_fills)): + trades = await bg.get_recent_trades("BTCUSDT") + assert [t["time"] for t in trades] == [1000, 2000] + assert trades[0]["is_buyer_maker"] is False + assert trades[1]["is_buyer_maker"] is True + finally: + await bg.close() + + +@pytest.mark.anyio +async def test_signals_router_naive_timestamp_and_ai_prompt_null_fields_and_key_isolation(): + """ + 1. signals.get_all_signals handles naive and 'Z' ISO updated_at timestamps without triggering false stale refreshes. + 2. ai._build_ai_prompt tolerates None values inside nested dicts and avoids double '$$'. + 3. ai.analyze_pair does not leak OPENAI_API_KEY to groq/openrouter providers when API key is missing. + """ + fresh_z = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + fresh_naive = (datetime.now(timezone.utc) - timedelta(seconds=10)).replace(tzinfo=None).isoformat() + sample_signals = [ + {"signal_data": {"symbol": "BTCUSDT", "updated_at": fresh_z}}, + {"signal_data": {"symbol": "ETHUSDT", "updated_at": fresh_naive}}, + ] + fake_req = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(collector=object()))) + bg_tasks = BackgroundTasks() + + orig_trigger = signals_router._last_batch_trigger_time + signals_router._last_batch_trigger_time = 0.0 + try: + with patch("routers.signals.async_get_latest_signals", AsyncMock(return_value=sample_signals)): + out = await signals_router.get_all_signals(fake_req, bg_tasks) + assert len(out) == 2 + assert len(bg_tasks.tasks) == 0 + finally: + signals_router._last_batch_trigger_time = orig_trigger + + signal_with_nones = { + "symbol": "SOLUSDT", + "direction": "NEUTRAL", + "conviction": 0, + "exchange_data": { + "binance": {"mark_price": 150.0, "index_price": 150.0, "oi": 10000.0}, + "hyperliquid": {"mark_price": 150.2, "basis_pct": None, "funding_rate": 0.0001, "oi": 5000.0}, + }, + "lead_lag": {"max_spread_bps": None, "max_spread_usd": 0.2}, + "price_extremes": { + "high_24h": None, + "low_24h": None, + "range_usd": None, + "range_pct": None, + "dist_to_high_pct": None, + "dist_to_low_pct": None, + "range_position_pct": None, + "zone_label": None, + }, + "predictive": { + "volatility_squeeze": {"squeeze_intensity": None, "compression_ratio": None}, + "orderbook_skew": {"bid_depth_usd": None, "ask_depth_usd": None}, + "liquidation_magnets": {"dist_upper_pct": None, "dist_lower_pct": None}, + "target_dist_pct": None, + }, + "signals": { + "cross_exchange": {"divergence_pct": None}, + "whale_order_flow": {"score": None, "label": None}, + "market_structure": {"tf": None, "structure_per_tf": {"1d": None}}, + }, + } + prompt_text, summary = ai_router._build_ai_prompt("SOLUSDT", signal_with_nones, []) + assert "$$" not in prompt_text + assert summary["compression_ratio"] == 1.0 + assert summary["depth_ratio"] == 1.0 + + # Groq provider without explicit api_key must raise 400 rather than stealing OPENAI_API_KEY + req_obj = SimpleNamespace(headers={}, app=SimpleNamespace(state=SimpleNamespace(collector=None))) + with patch.dict(os.environ, {"OPENAI_API_KEY": "sk-should-not-leak", "GROQ_API_KEY": ""}, clear=False): + with pytest.raises(ai_router.HTTPException) as exc_info: + await ai_router.analyze_pair( + ai_router.AIAnalyzeRequest(symbol="BTC/USDT", provider="groq"), + req_obj, + ) + assert exc_info.value.status_code == 400 + + +@pytest.mark.anyio +async def test_bybit_get_signature_matches_exact_query_string(): + """GET query string on HTTP wire must match exact sorted query signed in X-BAPI-SIGN.""" + executor = BybitExecutor(api_key="test_key", api_secret="test_secret", mode="demo") + fake_resp = MagicMock() + fake_resp.status_code = 200 + fake_resp.json.return_value = {"retCode": 0, "result": {"list": []}} + executor._client.get = AsyncMock(return_value=fake_resp) + + try: + # Deliberately pass unsorted insertion-order dict + await executor._request( + "GET", + "/v5/order/realtime", + params={"symbol": "BTCUSDT", "category": "linear", "orderId": "ord-1"}, + ) + args, kwargs = executor._client.get.await_args + assert args[0] == "/v5/order/realtime?category=linear&orderId=ord-1&symbol=BTCUSDT" + assert "params" not in kwargs + sent_headers = kwargs["headers"] + expected_sig = executor._generate_signature( + sent_headers["X-BAPI-TIMESTAMP"], + "category=linear&orderId=ord-1&symbol=BTCUSDT", + ) + assert sent_headers["X-BAPI-SIGN"] == expected_sig + finally: + await executor.close() + + +@pytest.mark.anyio +async def test_bybit_decimal_split_tp2_no_scientific_notation_and_limit_fallback_price(): + """ + 1. _format_num never produces scientific notation (e.g. '1e-05') in Bybit V5 string fields. + 2. Decimal subtraction preserves TP2 qty (0.3 - 0.2 == 0.1, avoiding IEEE 754 floor-to-zero). + 3. Limit orders always include 'price' using mark_price fallback when entry_price is omitted. + 4. Symbols like 'MEME/USDT' normalize cleanly to 'MEMEUSDT'. + """ + assert BybitExecutor._format_num(1e-5, 1e-5) == "0.00001" + assert BybitExecutor._format_num(1e-6) == "0.000001" + assert BybitExecutor._format_num(100.0, 0.5) == "100.0" + assert BybitExecutor._format_num(100.0, 1.0) == "100" + assert BybitExecutor._format_num(110.0) == "110.0" + + executor = BybitExecutor(api_key="test_key", api_secret="test_secret", mode="demo") + captured_payload: dict = {} + + async def _fake_request(method, path, params=None, json_body=None): + if method == "POST" and path == "/v5/order/create": + captured_payload.update(json_body or {}) + return {"retCode": 0, "result": {"orderId": "limit_order_1"}} + + try: + with patch.object( + executor, + "get_instrument_info", + AsyncMock(return_value={ + "symbol": "MEMEUSDT", + "base_coin": "MEME", + "quote_coin": "USDT", + "qty_step": 0.1, + "min_order_qty": 0.1, + "max_order_qty": 1_000_000.0, + "tick_size": 0.000001, + "min_price": 0.000001, + "max_price": 100.0, + }), + ), patch.object(executor, "set_leverage", AsyncMock(return_value=True)), \ + patch.object(executor, "_request", side_effect=_fake_request): + res = await executor.execute_trade_setup( + symbol="MEME/USDT", + side="Buy", + order_type="Limit", + margin_usd=0.000001, + leverage=3, + stop_loss=0.000008, + take_profit_1=0.000012, + take_profit_2=0.000015, + tp1_percent=67.0, + entry_price=None, + mark_price=0.00001, + ) + + assert res["symbol"] == "MEMEUSDT" + assert res["total_qty"] == pytest.approx(0.3) + assert captured_payload["symbol"] == "MEMEUSDT" + assert captured_payload["price"] == "0.000010" + assert captured_payload["stopLoss"] == "0.000008" + assert captured_payload["takeProfit"] == "0.000012" + assert captured_payload["tpSize"] == "0.2" + assert captured_payload["qty"] == "0.3" + assert "e-" not in captured_payload["price"].lower() + assert len(res["tp_orders"]) == 2 + assert res["tp_orders"][0]["qty"] == pytest.approx(0.2) + assert res["tp_orders"][1]["qty"] == pytest.approx(0.1) + finally: + await executor.close() + + +def test_outcome_evaluator_naive_datetime_utc_and_none_shadow_fallback(): + """Naive datetimes/ISO strings normalize as UTC and None primary keys fall back cleanly.""" + aware = datetime(2026, 3, 15, 12, 30, 0, tzinfo=timezone.utc) + naive = datetime(2026, 3, 15, 12, 30, 0) + assert _to_epoch_ms(naive) == _to_epoch_ms(aware) + assert _to_epoch_ms("2026-03-15T12:30:00") == _to_epoch_ms("2026-03-15T12:30:00Z") + + pred = { + "direction": "LONG", + "entry_price": None, + "entry": 100.0, + "stop_loss": 95.0, + "tp1": None, + "take_profit_1": 105.0, + "tp2": None, + "take_profit_2": 110.0, + "created_at": 1_000, + "expires_at": 500_000, + } + candles = [{"timestamp": 60_000, "high": 112.0, "low": 99.0, "close": 111.0}] + res = evaluate_prediction_against_candles(pred, candles, now_ts=100_000) + assert res is not None + assert res[0] == "TP2" + assert res[1] == pytest.approx(110.0) + + +def test_signal_engine_handles_none_trade_time_qty_and_candle_close(): + """Signal helpers tolerate None values in trade timestamps/qty and candle closes without TypeError.""" + spot = [{"time": None, "qty": None, "is_buyer_maker": False}] + [ + {"time": 1_000 + i * 100, "qty": 50.0, "is_buyer_maker": False} for i in range(6) + ] + fut = [{"time": None, "qty": None, "is_buyer_maker": True}] + [ + {"time": 1_000 + i * 100, "qty": 40.0, "is_buyer_maker": True} for i in range(6) + ] + + sf = _compute_spot_futures_cvd({"spot_trades": spot, "trades": fut}, None) + assert isinstance(sf, dict) + assert sf["spot_cvd"] > 0 + assert sf["futures_cvd"] < 0 + + cvd = _compute_cvd(spot) + assert isinstance(cvd, dict) + assert cvd["value"] > 0 + + none_candles = [{"close": None}, {"close": None}] + oi_res = _compute_oi_divergence( + {"open_interest_data": {"open_interest": 1000.0, "oi_change_pct": 1.0}, "ohlcv": {"15m": none_candles}}, + None, + None, + None, + ) + assert isinstance(oi_res, dict) + + cx_res = _compute_cross_exchange( + {"ohlcv": {"5m": none_candles}}, + {"ohlcv": {"5m": none_candles}}, + ) + assert isinstance(cx_res, dict) + assert cx_res["divergence_pct"] == 0.0 + + +@pytest.mark.anyio +async def test_exchange_hardening_bitget_orderbook_sort_binance_tf_and_bybit_empty_strings(): + """Verify Bitget orderbook sorting, Binance 3m/30m/2h intervals, and Bybit empty-string ticker guards.""" + assert {"3m", "30m", "2h"}.issubset(BINANCE_TF_MAP.keys()) + + bg = BitgetClient() + byb = BybitClient() + try: + unsorted_book = { + "bids": [["99.0", "5"], ["101.0", "10"], ["100.0", "7"]], + "asks": [["104.0", "3"], ["102.0", "8"], ["103.0", "4"]], + } + with patch.object(bg, "_get", AsyncMock(return_value=unsorted_book)): + ob = await bg.get_orderbook("BTCUSDT", depth=2) + assert ob["bids"] == [[101.0, 10.0], [100.0, 7.0]] + assert ob["asks"] == [[102.0, 8.0], [103.0, 4.0]] + + empty_ticker = {"list": [{"markPrice": "", "indexPrice": None, "fundingRate": ""}]} + with patch("exchanges.bybit.bulk_fetcher.get_bybit_mark_price", return_value=None), \ + patch("exchanges.bybit.bulk_fetcher.get_bybit_funding_rate", return_value=None), \ + patch.object(byb, "_get", AsyncMock(return_value=empty_ticker)): + mp = await byb.get_mark_price("BTCUSDT") + fr = await byb.get_funding_rate("BTCUSDT") + assert mp["mark_price"] == 0.0 + assert mp["index_price"] == 0.0 + assert fr["funding_rate"] == 0.0 + finally: + await bg.close() + await byb.close() + + +def test_symbol_resolver_preserves_k_tickers_and_strips_valid_multipliers(): + """Tickers starting with K (KAVA, KAS, KSM, KNC) must never lose their leading K.""" + from engine.symbol_resolver import get_symbol_variations, strip_multiplier_prefix + + assert strip_multiplier_prefix("KAVAUSDT") == "KAVAUSDT" + assert strip_multiplier_prefix("KASUSDT") == "KASUSDT" + assert strip_multiplier_prefix("KSMUSDT") == "KSMUSDT" + assert strip_multiplier_prefix("KNCUSDT") == "KNCUSDT" + assert strip_multiplier_prefix("1INCHUSDT") == "1INCHUSDT" + assert strip_multiplier_prefix("1000PEPEUSDT") == "PEPEUSDT" + assert strip_multiplier_prefix("kPEPE") == "PEPE" + assert strip_multiplier_prefix("KPEPEUSDT") == "PEPEUSDT" + + kava_vars = get_symbol_variations("KAVAUSDT") + assert "KAVAUSDT" in kava_vars + assert "AVAUSDT" not in kava_vars + assert "AVA" not in kava_vars + + pepe_vars = get_symbol_variations("kPEPE") + assert "PEPEUSDT" in pepe_vars + assert "kPEPE" in pepe_vars + + +@pytest.mark.anyio +async def test_ai_ssrf_and_key_exfiltration_blocked_and_non_usdt_preserved(monkeypatch): + """Custom base_url must not receive server env keys, must reject non-custom providers and private IPs, and preserve BTCUSDC.""" + from fastapi import HTTPException + from fastapi.testclient import TestClient + import main as main_module + + monkeypatch.setenv("VIKEY_API_KEY", "vk-server-secret-token") + + assert ai_router.resolve_ai_api_key("vikey", None, None, "https://attacker.example") is None + assert ai_router.resolve_ai_api_key("custom", None, None, None) is None + assert ai_router.resolve_ai_api_key("vikey", None, None, None) == "vk-server-secret-token" + + for bad_url in ( + "http://127.0.0.1:8080", + "http://localhost:8000", + "http://169.254.169.254/latest/meta-data", + "ftp://example.com/v1", + "https://user:pass@example.com/v1", + ): + with pytest.raises(HTTPException) as exc_info: + ai_router._validate_ai_base_url(bad_url) + assert exc_info.value.status_code == 400 + + with pytest.raises(HTTPException) as non_custom_exc: + await ai_router.execute_llm_completion( + provider="vikey", + clean_api_key="vk-test-key", + model_name=None, + prompt="hello", + base_url="https://attacker.example", + ) + assert non_custom_exc.value.status_code == 400 + + ai_router._AI_CACHE.clear() + captured_symbols: list[str] = [] + + async def _fake_completion(**kwargs): + captured_symbols.append(kwargs.get("context_label", "")) + return (f"BIAS: LONG — mock {kwargs.get('base_url')}", "custom-model") + + client = TestClient(main_module.app) + with patch("routers.ai.async_get_latest_signal", AsyncMock(return_value={"symbol": "BTCUSDC", "direction": "LONG", "conviction": 7})), \ + patch("routers.ai.async_get_latest_snapshot", AsyncMock(return_value=[])), \ + patch("routers.signals.get_market_regime", AsyncMock(return_value={"regime": "BULLISH"})), \ + patch("database.db.async_get_active_damian_memory", AsyncMock(return_value=[])), \ + patch("routers.ai.execute_llm_completion", side_effect=_fake_completion): + r1 = client.post( + "/api/ai/analyze", + json={"symbol": "BTC/USDC", "provider": "custom", "api_key": "ck-1", "base_url": "https://one.example.com"}, + ) + assert r1.status_code == 200 + assert r1.json()["symbol"] == "BTCUSDC" + assert captured_symbols[-1] == "BTCUSDC" + + r2 = client.post( + "/api/ai/analyze", + json={"symbol": "BTC/USDC", "provider": "custom", "api_key": "ck-1", "base_url": "https://two.example.com"}, + ) + assert r2.status_code == 200 + assert r2.json()["is_cached"] is False + ai_router._AI_CACHE.clear() + + +def test_mtf_analyzer_skips_none_closes_in_atr_stretch(): + """_calc_atr_stretch must tolerate None close entries without raising TypeError.""" + from engine.mtf_analyzer import _calc_atr_stretch + + candles = [{"high": 102.0 + i * 0.2, "low": 99.0 + i * 0.2, "close": 100.0 + i * 0.2} for i in range(18)] + candles.append({"high": 105.0, "low": 102.0, "close": None}) + candles.append({"high": 106.0, "low": 103.0, "close": 104.5}) + stretch = _calc_atr_stretch(candles) + assert isinstance(stretch, float) + + +def test_ws_safe_json_and_chart_okx_fallback(): + """WebSocket serialization replaces NaN/Inf cleanly and ws_chart falls back to OKX/Bitget mark prices.""" + import json + from fastapi import FastAPI + from fastapi.testclient import TestClient + from routers import ws as ws_router + + encoded = ws_router._safe_json_dumps({"price": float("nan"), "inf": float("inf"), "ok": 42.5}) + assert "NaN" not in encoded and "Infinity" not in encoded + decoded = json.loads(encoded) + assert decoded["price"] is None and decoded["inf"] is None and decoded["ok"] == 42.5 + + ws_app = FastAPI() + ws_app.include_router(ws_router.router) + ws_app.state.binance = SimpleNamespace(get_mark_price=AsyncMock(return_value=None)) + ws_app.state.bybit = SimpleNamespace(get_mark_price=AsyncMock(return_value=None)) + ws_app.state.okx = SimpleNamespace(get_mark_price=AsyncMock(return_value={"mark_price": 55.25})) + ws_app.state.bitget = SimpleNamespace(get_mark_price=AsyncMock(return_value=None)) + + with patch("routers.ws.bulk_fetcher.get_binance_mark_price", return_value=None), \ + patch("routers.ws.bulk_fetcher.get_bybit_mark_price", return_value=None): + client = TestClient(ws_app) + with client.websocket_connect("/ws/chart/OKB-USDT") as ws: + init_msg = json.loads(ws.receive_text()) + tick_msg = json.loads(ws.receive_text()) + assert init_msg["type"] == "chart_init" + assert tick_msg["type"] == "chart_tick" + assert tick_msg["symbol"] == "OKBUSDT" + assert tick_msg["price"] == pytest.approx(55.25) + assert tick_msg["exchanges"]["okx"] == pytest.approx(55.25) + + +def test_signals_cron_auth_enforced_and_db_json_sanitized(monkeypatch): + """GET /api/signals/cron must enforce token auth and DB JSON dumps must sanitize NaN values.""" + import json + from fastapi.testclient import TestClient + from database import db + import main as main_module + import security + + monkeypatch.setattr(security, "PERPS_API_TOKEN", "top-secret-token") + monkeypatch.setattr(security, "CRON_SECRET", None) + client = TestClient(main_module.app) + + unauth = client.get("/api/signals/cron") + assert unauth.status_code == 401 + + auth_ok = client.get("/api/signals/cron", headers={"Authorization": "Bearer top-secret-token"}) + assert auth_ok.status_code == 200 + + sanitized_str = db._safe_json_dumps({"conviction": 8, "delta": float("nan"), "nested": [float("inf")]}) + parsed = json.loads(sanitized_str) + assert parsed == {"conviction": 8, "delta": None, "nested": [None]} + assert hasattr(db, "_predictions_table_lock") + + +@pytest.mark.anyio +async def test_serve_spa_blocks_directory_traversal(): + """serve_spa must reject path traversal attempts outside STATIC_DIR with HTTP 404.""" + from fastapi import HTTPException + import main as main_module + + assert hasattr(main_module, "serve_spa") + with pytest.raises(HTTPException) as exc_info: + await main_module.serve_spa("../../backend/.env") + assert exc_info.value.status_code == 404 + + +@pytest.mark.anyio +async def test_spot_symbol_cleaning_and_okx_non_usdt_probe(monkeypatch): + """Spot market checks must preserve K-initial tickers (KAVA/KAS/KSM) and support non-USDT OKX pairs.""" + from engine import data_collector + + assert data_collector._clean_spot_symbol("KAVAUSDT") == "KAVAUSDT" + assert data_collector._clean_spot_symbol("KASUSDT") == "KASUSDT" + assert data_collector._clean_spot_symbol("KSMUSDT") == "KSMUSDT" + assert data_collector._clean_spot_symbol("1000PEPEUSDT") == "PEPEUSDT" + assert data_collector._clean_spot_symbol("kPEPE/USDT") == "PEPEUSDT" + + requested_urls: list[str] = [] + + class _FakeResp: + def __init__(self, status_code: int, payload: dict): + self.status_code = status_code + self._payload = payload + + def json(self) -> dict: + return self._payload + + class _FakeClient: + async def get(self, url: str): + requested_urls.append(url) + if "instId=PEPE-USDC" in url: + return _FakeResp(200, {"data": [{"instId": "PEPE-USDC"}]}) + return _FakeResp(404, {"data": [], "result": {"list": []}}) + + monkeypatch.setattr(data_collector, "_SPOT_VERIFICATION_CACHE", {}) + monkeypatch.setattr(data_collector, "_get_spot_http_client", lambda: _FakeClient()) + + await data_collector.check_spot_market_exists("KAVAUSDT") + assert not any("AVAUSDT" in url and "KAVAUSDT" not in url for url in requested_urls) + + requested_urls.clear() + has_spot = await data_collector.check_spot_market_exists("1000PEPEUSDC") + assert has_spot is True + assert any("instId=PEPE-USDC" in url for url in requested_urls) + + +@pytest.mark.anyio +async def test_binance_get_spot_trades_preserves_k_tickers_and_non_usdt(monkeypatch): + """BinanceClient.get_spot_trades must never strip leading 'K' from KAVAUSDT while handling 1000PEPEUSDC.""" + from exchanges.binance import BinanceClient + + queried_symbols: list[str] = [] + + class _FakeResp: + def __init__(self, status_code: int, payload): + self.status_code = status_code + self._payload = payload + + def json(self): + return self._payload + + class _FakeClient: + async def get(self, url: str, params=None): + sym = (params or {}).get("symbol", "") + queried_symbols.append(sym) + if sym == "PEPEUSDC": + return _FakeResp(200, [{"price": "0.00001", "qty": "100", "isBuyerMaker": False, "time": 1}]) + return _FakeResp(400, []) + + async def aclose(self): + return None + + client = BinanceClient() + monkeypatch.setattr(client, "_client", _FakeClient()) + + await client.get_spot_trades("KAVAUSDT") + assert queried_symbols == ["KAVAUSDT"] + + queried_symbols.clear() + trades = await client.get_spot_trades("1000PEPEUSDC") + assert queried_symbols == ["1000PEPEUSDC", "PEPEUSDC"] + assert len(trades) == 1 + await client.close() + + +def test_okx_to_inst_id_non_usdt_and_slashes(): + """OKXClient._to_inst_id cold-cache fallback must format USDC/USD/EUR pairs and strip delimiters.""" + from exchanges.okx import OKXClient + + client = OKXClient() + assert client._to_inst_id("BTC/USDC") == "BTC-USDC-SWAP" + assert client._to_inst_id("BTC-USDC") == "BTC-USDC-SWAP" + assert client._to_inst_id("ETH/EUR") == "ETH-EUR-SWAP" + assert client._to_inst_id("BTC-USDC-SWAP") == "BTC-USDC-SWAP" + + +@pytest.mark.anyio +async def test_multi_stream_preserves_zero_funding_and_open_interest(monkeypatch): + """get_multi_exchange_stream must preserve 0.0 funding_rate and open_interest instead of coalescing to None.""" + from types import SimpleNamespace + from routers import market as market_router + + class _DummyExchange: + async def get_mark_price(self, _sym: str): + return {"mark_price": 95000.0, "index_price": 95000.0} + + async def get_funding_rate(self, _sym: str): + return {"funding_rate": 0.0001} + + async def get_open_interest(self, _sym: str): + return {"open_interest": 1234.0} + + monkeypatch.setattr(market_router.bulk_fetcher, "get_binance_mark_price", lambda _s: {"mark_price": 95000.0, "index_price": 95000.0}) + monkeypatch.setattr(market_router.bulk_fetcher, "get_binance_funding_rate", lambda _s: {"funding_rate": 0.0}) + monkeypatch.setattr(market_router.bulk_fetcher, "get_bybit_mark_price", lambda _s: {"mark_price": 95005.0, "index_price": 95000.0}) + monkeypatch.setattr(market_router.bulk_fetcher, "get_bybit_funding_rate", lambda _s: {"funding_rate": 0.0}) + monkeypatch.setattr(market_router.bulk_fetcher, "get_bybit_24h_and_oi", lambda _s: {"open_interest": 0.0}) + + fake_req = SimpleNamespace( + app=SimpleNamespace( + state=SimpleNamespace( + binance=_DummyExchange(), + bybit=_DummyExchange(), + okx=None, + bitget=None, + hyperliquid=None, + ) + ) + ) + + res = await market_router.get_multi_exchange_stream("BTCUSDT", fake_req) + assert res["exchanges"]["binance"]["funding_rate"] == 0.0 + assert res["exchanges"]["bybit"]["funding_rate"] == 0.0 + assert res["exchanges"]["bybit"]["open_interest"] == 0.0 + + +def test_signal_engine_ohlcv_fallback_tolerates_none_and_zero_volume(): + """OHLCV delta fallback in SignalEngine.compute must ignore None OHLC bars and not inflate 0.0 volume to 1.0.""" + from engine.signal_engine import SignalEngine + + candles = [ + {"timestamp": i * 900_000, "open": 100.0, "high": 102.0, "low": 99.0, "close": 101.0, "volume": 0.0, "taker_buy_volume": None} + for i in range(12) + ] + candles[-1] = { + "timestamp": 12 * 900_000, + "open": None, + "high": 102.0, + "low": 99.0, + "close": None, + "volume": None, + "taker_buy_volume": None, + } + + raw = { + "symbol": "TESTUSDT", + "binance": { + "mark_price": {"mark_price": 101.0, "index_price": 101.0}, + "ohlcv": {"15m": candles}, + }, + "bybit": None, + "okx": None, + "hyperliquid": None, + "bitget": None, + } + + sig = SignalEngine().compute(raw, horizon_thresholds={"cvd_min_notional": 1000}) + assert sig["symbol"] == "TESTUSDT" + assert sig["signals"]["cvd"]["score"] == 0 + assert "OHLCV Candle Volume Delta" not in str(sig["signals"]["cvd"].get("label", "")) + + +def test_ai_http_client_disables_redirects(): + """Shared AI HTTP client must set follow_redirects=False so SSRF IP validation cannot be bypassed via 302.""" + from routers import ai as ai_router + + client = ai_router.get_ai_http_client() + assert client.follow_redirects is False + + +def test_execution_journal_logs_100pct_tp1_without_runner_and_subcent_prices(monkeypatch): + """Auto-journal entry must log 100% TP1 when there is no TP2 runner and preserve sub-cent precision.""" + from fastapi.testclient import TestClient + import main as main_module + from routers import execution as execution_router + import security + + captured_journal: dict = {} + + class _FakeExecutor: + api_key = "k" + api_secret = "s" + mode = "demo" + + async def execute_trade_setup(self, **_kwargs): + return { + "symbol": "1000PEPEUSDT", + "side": "Buy", + "mode": "demo", + "entry_order_id": "ord-123", + "total_qty": 1000.0, + "tp1_qty": 1000.0, + "tp2_qty": 0.0, + "tp_orders": [{"tp_level": "TP1", "qty": 1000.0, "order_id": "tp-1"}], + } + + async def close(self): + return None + + async def _fake_journal_create(entry: dict): + captured_journal.update(entry) + return entry + + monkeypatch.setattr(security, "PERPS_API_TOKEN", "exec-secret-token") + monkeypatch.setattr(execution_router, "_get_active_executor", lambda **_kwargs: (_FakeExecutor(), "test")) + monkeypatch.setattr(execution_router, "async_create_journal_entry", _fake_journal_create) + + client = TestClient(main_module.app) + resp = client.post( + "/api/execution/bybit/order", + headers={"Authorization": "Bearer exec-secret-token"}, + json={ + "symbol": "1000PEPE/USDT", + "side": "Buy", + "order_type": "Limit", + "margin_usd": 50.0, + "leverage": 5, + "entry_price": 0.00001234, + "stop_loss": 0.0000112, + "take_profit_1": 0.0000145, + "take_profit_2": None, + "tp1_percent": 50.0, + "log_to_journal": True, + }, + ) + assert resp.status_code == 200 + assert captured_journal["symbol"] == "1000PEPEUSDT" + assert captured_journal["entry_zone"] == "$0.00001234" + assert captured_journal["stop_loss"] == "$0.0000112" + assert captured_journal["take_profit"] == "TP1: $0.0000145 (100%)" + assert captured_journal["snapshot_data"]["tp1_percent"] == 100.0 + + + + +# --------------------------------------------------------------------------- +# Pass-4 Deep Audit Regression Tests +# --------------------------------------------------------------------------- + + +def test_predictive_engine_magnets_tolerates_none_ohlc(): + """_compute_liquidation_magnets must ignore None high/low candle fields instead of raising TypeError.""" + from engine.predictive_engine import _compute_liquidation_magnets + + candles = [ + {"high": None, "low": None, "close": 100.0}, + {"high": 105.0, "low": 96.0, "close": 100.0}, + {"high": 104.0, "low": 97.0, "close": 101.0}, + ] + res = _compute_liquidation_magnets(mark_price=100.0, ohlcv_1h=candles) + assert res["upper_magnet"] > 105.0 + assert res["lower_magnet"] < 96.0 + + +def test_outcome_evaluator_skips_none_ohlc_and_zero_low_bars(): + """evaluate_prediction_against_candles must skip None/0 OHLC bars without crashing or falsely triggering SL.""" + t0 = 1_700_000_000_000 + pred = { + "direction": "LONG", + "entry_price": 100.0, + "stop_loss": 95.0, + "tp1": 105.0, + "tp2": 110.0, + "created_at": t0, + "expires_at": t0 + 3600_000, + } + candles = [ + {"timestamp": t0 + 600_000, "high": None, "low": None, "close": None}, + {"timestamp": t0 + 1200_000, "high": 111.0, "low": 99.0, "close": 110.5}, + ] + res = evaluate_prediction_against_candles(pred, candles, now_ts=t0 + 1800_000) + assert res is not None + outcome, _, r_mult = res + assert outcome == "TP2" + assert r_mult > 0 + + # Also test EXPIRED path where final bar has close=None -> falls back to prior valid close + pred_exp = { + "direction": "LONG", + "entry_price": 100.0, + "stop_loss": 90.0, + "tp1": 120.0, + "tp2": 130.0, + "created_at": t0, + "expires_at": t0 + 3600_000, + } + candles_exp = [ + {"timestamp": t0 + 1200_000, "high": 103.0, "low": 98.0, "close": 102.0}, + {"timestamp": t0 + 2400_000, "high": 103.0, "low": 99.0, "close": None}, + ] + res_exp = evaluate_prediction_against_candles(pred_exp, candles_exp, now_ts=t0 + 7200_000) + assert res_exp is not None + assert res_exp[0] == "EXPIRED" + assert res_exp[1] == 102.0 + + +def test_fake_detector_tolerates_none_candles_and_multielem_orderbook(): + """fake_detector helpers must tolerate None OHLCV fields and >2-element orderbook levels.""" + from engine.fake_detector import ( + _orderbook_imbalance_detected, + _wash_trade_detected, + _wick_sweep_detected, + ) + + wick_candles = [ + {"open": None, "high": None, "low": None, "close": None}, + {"open": 100.0, "high": 105.0, "low": 99.5, "close": 100.2}, + {"open": 100.2, "high": 101.0, "low": 99.9, "close": 100.5}, + ] + has_wick, _ = _wick_sweep_detected(wick_candles) + assert has_wick is True + + wash_candles = [ + {"open": 100.0, "high": 101.0, "low": 99.0, "close": 100.5, "volume": 10.0} + for _ in range(19) + ] + [ + {"open": None, "high": None, "low": None, "close": None, "volume": None}, + {"open": 100.0, "high": 100.5, "low": 99.5, "close": 100.1, "volume": 100.0}, + {"open": 100.0, "high": 100.1, "low": 99.9, "close": 100.0, "volume": 1.0}, + ] + assert _wash_trade_detected(wash_candles) is True + + ob = { + "bids": [[100.0, 1000.0, "0", "5"]], + "asks": [[101.0, 10.0, "0", "1"]], + } + flagged, label = _orderbook_imbalance_detected(ob, cvd_matches_price=False) + assert flagged is True + assert "Bid Wall Imbalance" in label + + +@pytest.mark.anyio +async def test_bybit_executor_empty_list_response_guards(): + """BybitExecutor must handle empty result.list arrays gracefully instead of raising IndexError.""" + executor = BybitExecutor(api_key="test-k", api_secret="test-s", mode="demo") + + async def _fake_request(_method: str, path: str, _params: dict | None = None, json_body: dict | None = None): + if "wallet-balance" in path: + return {"result": {"list": []}} + if "instruments-info" in path: + return { + "result": { + "list": [ + { + "lotSizeFilter": {"qtyStep": "1", "minOrderQty": "1"}, + "priceFilter": {"tickSize": "0.01"}, + } + ] + } + } + if "position/set-leverage" in path: + return {"retCode": 0, "result": {}} + if "market/tickers" in path: + return {"result": {"list": []}} + return {"result": {}} + + executor._request = _fake_request # type: ignore[method-assign] + bal = await executor.get_wallet_balance() + assert bal["available_balance"] == 0.0 + assert bal["total_equity"] == 0.0 + + with pytest.raises(ValueError, match="Tidak dapat menentukan harga acuan"): + await executor.execute_trade_setup( + symbol="BTCUSDT", + side="Buy", + order_type="Market", + margin_usd=50.0, + leverage=5, + stop_loss=90.0, + take_profit_1=110.0, + entry_price=None, + mark_price=None, + ) + await executor.close() + + +@pytest.mark.anyio +async def test_bybit_spot_trades_probes_raw_and_stripped_multiplier_symbol(): + """BybitClient.get_spot_trades must probe raw_sym first then stripped spot symbol on multiplier tokens.""" + queried: list[str] = [] + client = BybitClient() + + async def _fake_get(_path: str, params: dict | None = None): + sym = (params or {}).get("symbol", "") + queried.append(sym) + if sym == "1000PEPEUSDT": + return {"list": []} + return { + "list": [ + {"price": "0.000012", "size": "1000", "side": "Buy", "time": "1700000002000"}, + {"price": "0.000011", "size": "500", "side": "Sell", "time": "1700000001000"}, + ] + } + + client._get = _fake_get # type: ignore[method-assign] + trades = await client.get_spot_trades("1000PEPEUSDT") + assert queried == ["1000PEPEUSDT", "PEPEUSDT"] + assert len(trades) == 2 + assert trades[0]["time"] < trades[1]["time"] + assert trades[0]["is_buyer_maker"] is True + assert trades[1]["is_buyer_maker"] is False + await client.close() + + +@pytest.mark.anyio +async def test_bitget_hyperliquid_symbol_and_okx_ratio_guards(): + """Verify Bitget symbol normalization, Hyperliquid delimiter/limit handling, and OKX negative ratio guard.""" + import time + from exchanges.hyperliquid import HyperliquidClient + from exchanges.okx import OKXClient + + bg = BitgetClient() + assert bg._to_bitget_symbol("btc/usdt") == "BTCUSDT" + assert bg._to_bitget_symbol("eth-usdt") == "ETHUSDT" + await bg.close() + + hl = HyperliquidClient() + assert hl._format_symbol("kPEPE/USDT") == "kPEPE" + assert hl._format_symbol("BTC-USDC") == "BTC" + assert hl._format_symbol("USD") == "USD" + hl._cached_universe = {"BTC": {}} + hl._coin_lookup = {"BTC": "BTC"} + hl._cache_time = time.time() + + fake_resp = MagicMock() + fake_resp.raise_for_status = MagicMock() + fake_resp.json.return_value = [ + {"px": "100", "sz": "1", "side": "B", "time": i} + for i in range(10) + ] + hl._client.post = AsyncMock(return_value=fake_resp) + trades = await hl.get_recent_trades("BTCUSDT", limit=3) + assert len(trades) == 3 + assert [t["time"] for t in trades] == [7, 8, 9] + await hl.close() + + okx = OKXClient() + okx._get = AsyncMock(return_value=[[1700000000000, "-1"]]) # type: ignore[method-assign] + ratio_res = await okx.get_long_short_ratio("BTCUSDT") + assert ratio_res is None + await okx.close() + + +def test_signal_engine_compute_trade_plan_none_ohlcv_and_swing_chased_dir_veto(monkeypatch): + """_compute_trade_plan tolerates None high/low bars; swing extreme SHORT veto populates vetoed_from='SHORT'.""" + from engine import signal_engine as se_mod + from engine.signal_engine import SignalEngine, _compute_trade_plan + + long_plan = _compute_trade_plan( + direction="LONG", + mark_price=100.0, + ohlcv_1h=[{"open": 100.0, "high": 101.0, "low": None, "close": 100.0}], + spot_futures_score=0, + conviction=5, + ) + short_plan = _compute_trade_plan( + direction="SHORT", + mark_price=100.0, + ohlcv_1h=[{"open": 100.0, "high": None, "low": 99.0, "close": 100.0}], + spot_futures_score=0, + conviction=5, + ) + assert long_plan["trade_levels"] is not None + assert short_plan["trade_levels"] is not None + + # Stub MTF analyzer + confluence scorer so intraday=NEUTRAL while swing raw SHORT is anti-chasing blocked + monkeypatch.setattr( + se_mod.mtf_analyzer, + "analyze", + lambda *_args, **_kwargs: { + "active_timeframe": "1h", + "market_condition": "CHOPPY", + "regime": "CHOPPY", + "atr_ratio": 1.0, + "score": 0, + "weighted_score": 0, + "structure": "ranging", + "tf": "1h", + "label": "Ranging / Mixed Structure", + "active_structure": "ranging", + "intraday_structure": 0, + "swing_structure": 0, + "structure_per_tf": {}, + "intraday_atr_stretch": 0.0, + "swing_atr_stretch": -3.5, + }, + ) + + def _fake_compute(_factors, horizon="primary", regime="CHOPPY", threshold_override=None): + is_swing = horizon == "swing" + return { + "score": -5 if is_swing else 0, + "direction": "SHORT" if is_swing else "NEUTRAL", + "conviction": 5 if is_swing else 0, + "effective_threshold": threshold_override or 4, + "horizon": horizon, + "regime": regime, + "weights_applied": {}, + "raw_score": -5 if is_swing else 0, + } + + monkeypatch.setattr(se_mod.confluence_scorer, "compute", _fake_compute) + + candles = [ + {"timestamp": i * 3_600_000, "open": 100.0, "high": 101.0, "low": 99.0, "close": 100.0, "volume": 1000.0} + for i in range(24) + ] + raw = { + "symbol": "SWINGSHORTUSDT", + "binance": { + "mark_price": {"mark_price": 100.0, "index_price": 100.0}, + "ohlcv": {"15m": candles, "1h": candles, "4h": candles}, + "orderbook": {"bids": [[99.9, 5000.0]], "asks": [[100.1, 5000.0]]}, + }, + "bybit": None, + "okx": None, + "bitget": None, + "hyperliquid": None, + } + + sig = SignalEngine().compute(raw) + assert sig["veto_reason"] == "ANTI_CHASING_EXTREME" + assert sig["confluence"]["vetoed_from"] == "SHORT" + assert sig["direction"] == "NEUTRAL" + + +def test_ai_prompt_sub_million_oi_not_double_multiplied_and_signal_none(): + """_build_ai_prompt must treat already-normalized USD OI as USD (no <1e6 * price) and tolerate signal=None.""" + snapshots = [ + {"exchange": "binance", "mark_price": 500.0, "oi": 250000.0, "funding_rate": 0.0001}, + {"exchange": "bybit", "mark_price": 500.0, "oi": 250000.0, "funding_rate": 0.0003}, + ] + prompt, summary = ai_router._build_ai_prompt( + symbol="ALTUSDT", + signal=None, + snapshots=snapshots, + ) + assert "$500.0K" in prompt + assert "$250.00M" not in prompt + assert summary["avg_fr_8h_pct"] == 0.02 + assert summary["annualized_apr_pct"] == 21.9 + assert summary["warnings"] == [] + + +@pytest.mark.anyio +async def test_market_candles_and_funding_history_tolerate_none_timestamp(): + """market endpoints must treat timestamp=None safely as 0 instead of raising TypeError.""" + from routers import market as market_router + + class _DummyBinance: + async def get_ohlcv(self, _sym: str, timeframe: str = "15m", limit: int = 150): + return [ + {"timestamp": None, "open": 100.0, "high": 102.0, "low": 99.0, "close": 101.0, "volume": 10.0}, + {"timestamp": 1700000000000, "open": 101.0, "high": 103.0, "low": 100.0, "close": 102.0, "volume": 20.0}, + ] + + async def get_oi_history(self, _sym: str, timeframe: str = "15m", limit: int = 150): + return [{"timestamp": None, "open_interest_usd": 500000.0}] + + async def get_funding_rate_history(self, _sym: str, limit: int = 30): + return [{"timestamp": None, "funding_rate": 0.0001}] + + class _DummyBybit: + async def get_ohlcv(self, _sym: str, timeframe: str = "15m", limit: int = 150): + return [{"timestamp": None, "open": 100.0, "high": 101.0, "low": 99.0, "close": 100.5, "volume": 5.0}] + + async def get_oi_history(self, _sym: str, timeframe: str = "15m", limit: int = 150): + return [{"timestamp": None, "open_interest": 100.0}] + + async def get_funding_rate_history(self, _sym: str, limit: int = 30): + return [{"timestamp": None, "funding_rate": 0.0002}] + + fake_req = SimpleNamespace( + app=SimpleNamespace( + state=SimpleNamespace( + binance=_DummyBinance(), + bybit=_DummyBybit(), + okx=None, + bitget=None, + hyperliquid=None, + ) + ) + ) + + candles_res = await market_router.get_market_candles("BTCUSDT", fake_req, timeframe="15m", limit=10, exchange=None) + assert candles_res["count"] == 2 + + funding_res = await market_router.get_market_funding_history("BTCUSDT", fake_req, limit=10) + assert funding_res["count"] == 1 + + +@pytest.mark.anyio +async def test_market_multi_stream_resolves_usd_notional_oi_across_all_venues(monkeypatch): + """ + /api/market/{symbol}/multi-stream feeds MultiExchangeLiveBoard fmtOi ($B/$M/$K). + Every exchange's open_interest must resolve to USD notional rather than raw base coin count. + """ + from types import SimpleNamespace + from routers import market as market_router + + monkeypatch.setattr(market_router.bulk_fetcher, "get_binance_mark_price", lambda _s: None) + monkeypatch.setattr(market_router.bulk_fetcher, "get_binance_funding_rate", lambda _s: None) + monkeypatch.setattr(market_router.bulk_fetcher, "get_bybit_mark_price", lambda _s: None) + monkeypatch.setattr(market_router.bulk_fetcher, "get_bybit_funding_rate", lambda _s: None) + monkeypatch.setattr(market_router.bulk_fetcher, "get_bybit_24h_and_oi", lambda _s: None) + + class _Binance: + async def get_mark_price(self, _s): + return {"mark_price": 50000.0, "index_price": 50000.0} + + async def get_funding_rate(self, _s): + return {"funding_rate": 0.0001} + + async def get_open_interest(self, _s): + return {"open_interest": 2000.0, "open_interest_value": 100_000_000.0} + + class _Bybit: + async def get_mark_price(self, _s): + return {"mark_price": 50010.0, "index_price": 50000.0} + + async def get_funding_rate(self, _s): + return {"funding_rate": 0.0001} + + async def get_open_interest(self, _s): + # Missing open_interest_value -> must fallback to coins * bybit_price + return {"open_interest": 1000.0, "open_interest_value": None} + + class _Okx: + async def get_mark_price(self, _s): + return {"mark_price": 50020.0, "index_price": 50000.0} + + async def get_funding_rate(self, _s): + return {"funding_rate": 0.0001} + + async def get_open_interest(self, _s): + return {"open_interest": 500.0, "open_interest_value": 25_010_000.0} + + class _Bitget: + async def get_mark_price(self, _s): + return {"mark_price": 50030.0, "index_price": 50000.0} + + async def get_funding_rate(self, _s): + return {"funding_rate": 0.0001} + + async def get_open_interest(self, _s): + return {"open_interest": 400.0, "open_interest_value": 20_012_000.0} + + class _Hyperliquid: + async def get_market_data(self, _s): + # Hyperliquid reports openInterest in base coins -> must multiply by mark_price + return {"mark_price": 50040.0, "funding_rate": 0.0002, "open_interest": 300.0} + + fake_req = SimpleNamespace( + app=SimpleNamespace( + state=SimpleNamespace( + binance=_Binance(), + bybit=_Bybit(), + okx=_Okx(), + bitget=_Bitget(), + hyperliquid=_Hyperliquid(), + ) + ) + ) + + res = await market_router.get_multi_exchange_stream("BTCUSDT", fake_req) + ex = res["exchanges"] + assert ex["binance"]["open_interest"] == 100_000_000.0 + assert ex["bybit"]["open_interest"] == 50_010_000.0 + assert ex["okx"]["open_interest"] == 25_010_000.0 + assert ex["bitget"]["open_interest"] == 20_012_000.0 + assert ex["hyperliquid"]["open_interest"] == 15_012_000.0 + + +@pytest.mark.anyio +async def test_market_candles_skips_zero_timestamp_in_oi_history(): + """ + Invalid timestamp=0 / None entries in OI history must not become the LOCF baseline + for real candles. + """ + from types import SimpleNamespace + from routers import market as market_router + + class _Binance: + async def get_ohlcv(self, _sym: str, timeframe: str = "15m", limit: int = 150): + return [ + {"timestamp": 1700000000000, "open": 100.0, "high": 101.0, "low": 99.0, "close": 100.0, "volume": 10.0}, + {"timestamp": 1700000900000, "open": 100.0, "high": 102.0, "low": 100.0, "close": 101.0, "volume": 12.0}, + ] + + async def get_oi_history(self, _sym: str, timeframe: str = "15m", limit: int = 150): + return [ + {"timestamp": None, "open_interest_usd": 999_999_999.0}, + {"timestamp": 1700000900000, "open_interest_usd": 500_000.0}, + ] + + fake_req = SimpleNamespace( + app=SimpleNamespace( + state=SimpleNamespace(binance=_Binance(), bybit=None, okx=None, bitget=None, hyperliquid=None) + ) + ) + + res = await market_router.get_market_candles("BTCUSDT", fake_req, timeframe="15m", limit=10, exchange=None) + assert res["candles"][0]["open_interest"] == 500_000.0 + assert res["candles"][1]["open_interest"] == 500_000.0 + + +@pytest.mark.anyio +async def test_bybit_executor_reduce_only_tp_formats_integer_qty_without_decimal_noise(): + """ + reconcile_limit_tp2_once must format reduce-only TP qty and price using instrument + qty_step and tick_size so integer steps emit '100' rather than '100.0' and sub-cent + prices never emit scientific notation. + """ + from engine.execution.bybit_executor import BybitExecutor + + executor = BybitExecutor(api_key="test-key", api_secret="test-secret", mode="demo") + posted_payloads: list[dict] = [] + + async def _fake_get_inst(_sym: str): + return { + "symbol": "PEPEUSDT", + "qty_step": 1.0, + "tick_size": 0.000001, + "min_order_qty": 1.0, + } + + async def _fake_request(method: str, path: str, params=None, json_body=None): + if path == "/v5/order/realtime": + return {"result": {"list": [{"orderStatus": "Filled"}]}} + if path == "/v5/order/create" and json_body is not None: + posted_payloads.append(json_body) + return {"result": {"orderId": "tp2-order-1"}} + return {"result": {}} + + executor.get_instrument_info = _fake_get_inst # type: ignore[method-assign] + executor._request = _fake_request # type: ignore[method-assign] + + res = await executor.reconcile_limit_tp2_once( + symbol="PEPEUSDT", + entry_order_id="entry-1", + opposite_side="Sell", + tp2_qty=100.0, + tp2_price=0.000012, + percent=50.0, + ) + await executor.close() + + assert res["status"] == "PLACED" + assert len(posted_payloads) == 1 + assert posted_payloads[0]["qty"] == "100" + assert posted_payloads[0]["price"] == "0.000012" diff --git a/tests/test_sniper_accuracy.py b/tests/test_sniper_accuracy.py index cd80de4837b5ec1f72e43dba0f6420997a877e0b..65fd24ad69270355a8c239b096153725c485d348 100644 --- a/tests/test_sniper_accuracy.py +++ b/tests/test_sniper_accuracy.py @@ -477,3 +477,203 @@ def test_accuracy_routes_readonly_get_and_authenticated_post_evaluate(): assert data["by_factor"]["funding"]["opposing_trades"] == 2 +def test_five_layer_whale_intelligence_and_multi_horizon_oi(): + """Verify all 5 layers of Whale Movement Intelligence and Multi-Horizon OI Divergence.""" + from engine.signal_engine import ( + _compute_ls_ratio, + _compute_oi_divergence, + _compute_whale_order_flow, + ) + + # 1. Layer 1: Smart Money Whale Position vs Retail Crowd Divergence + binance_sm = { + "ls_ratio_data": { + "long_ratio": 0.65, + "short_ratio": 0.35, + "top_position_long_ratio": 0.65, + "retail_long_ratio": 0.44, + "whale_retail_delta": 0.21, + } + } + ls_res = _compute_ls_ratio(binance_sm, None, None, None) + assert ls_res["score"] == 2 + assert ls_res["smart_money_delta"] == 0.21 + assert "Smart Money Long" in ls_res["label"] + + # 2. Layer 2 (Sweep Clustering) + Layer 3 (Klines TWAP) + Layer 4 (Hyperliquid Wallet) + # 10 split child fills of $3,500 at exact same tick timestamp 1700000000 -> $35,000 reconstructed sweep! + split_sweep_buys = [ + {"venue": "binance", "time": 1700000000, "price": 100.0, "qty": 35.0, "is_buyer_maker": False} + for _ in range(10) + ] + hl_wallet_trades = [ + { + "venue": "hyperliquid", + "time": 1700000100 + i, + "price": 100.0, + "qty": 400.0, + "is_buyer_maker": False, + "taker_wallet": "0xwhale1234567890", + } + for i in range(2) + ] + twap_candles = [ + { + "timestamp": i * 900_000, + "open": 100.0, + "high": 101.0, + "low": 99.8, + "close": 100.8, + "volume": 1000.0, + "taker_buy_volume": 620.0, # 62% taker buy TWAP + } + for i in range(8) + ] + oi_bull = {"score": 2, "oi_change_pct": 2.4} + wf_res = _compute_whale_order_flow( + split_sweep_buys + hl_wallet_trades, + 100.0, + merged_ohlcv={"15m": twap_candles}, + oi_signal=oi_bull, + ls_signal=ls_res, + ) + assert wf_res["sweep_buy_count"] >= 1 + assert wf_res["sweep_buy_vol_usd"] >= 35_000.0 + assert wf_res["twap_bias"] in ("ACCUMULATION", "WHALE_TWAP_LONG_BUILDUP") + assert wf_res["onchain_whale_wallets"] == 1 + assert wf_res["top_whale_wallet_usd"] == 80_000.0 + assert wf_res["whale_composite_score"] == 2 + + # 3. Layer 5: Passive Iceberg Limit Absorption (Heavy Taker Sell absorbed by strong bullish close + OI up) + iceberg_sells = [ + {"venue": "binance", "time": 1700000500 + i * 10, "price": 100.0, "qty": 50.0, "is_buyer_maker": True} + for i in range(20) + ] + iceberg_buys = [ + {"venue": "binance", "time": 1700000800 + i * 10, "price": 100.0, "qty": 10.0, "is_buyer_maker": False} + for i in range(10) + ] + iceberg_candles = [ + {"timestamp": 1, "open": 100.0, "high": 100.5, "low": 99.5, "close": 100.0, "volume": 500.0}, + {"timestamp": 2, "open": 99.0, "high": 101.0, "low": 98.8, "close": 100.9, "volume": 800.0}, + ] + wf_ice = _compute_whale_order_flow( + iceberg_sells + iceberg_buys, + 100.9, + merged_ohlcv={"15m": iceberg_candles}, + oi_signal={"score": 1, "oi_change_pct": 1.2}, + ) + assert wf_ice["absorption_type"] == "BULLISH_ICEBERG_ABSORPTION" + assert wf_ice["whale_composite_score"] >= 1 + assert "Bullish" in wf_ice["flow_verdict"] + + # 3b. No-trade & malformed-trade fallback preserves klines TWAP/Iceberg verdict and volumes + wf_no_trades = _compute_whale_order_flow( + [], + 100.8, + merged_ohlcv={"15m": twap_candles}, + oi_signal={"score": 2, "oi_change_pct": 2.4}, + ) + assert wf_no_trades["twap_bias"] == "WHALE_TWAP_LONG_BUILDUP" + assert wf_no_trades["taker_buy_vol_usd"] > 0 + assert wf_no_trades["whale_composite_score"] >= 1 + assert "Akumulasi TWAP" in wf_no_trades["flow_verdict"] + + wf_bad_trades = _compute_whale_order_flow( + [{"price": 0.0, "qty": 0.0}], + 100.8, + merged_ohlcv={"15m": twap_candles}, + oi_signal={"score": 2, "oi_change_pct": 2.4}, + ) + assert wf_bad_trades["flow_verdict"] == wf_no_trades["flow_verdict"] + assert wf_bad_trades["whale_composite_score"] == wf_no_trades["whale_composite_score"] + + # 4. Multi-Horizon OI Divergence (15m short-covering pullback vs 4h macro long inflow) + b_oi = { + "open_interest_data": { + "open_interest": 100_000.0, + "open_interest_value": 10_000_000.0, + "oi_change_pct": -0.5, + "oi_change_1h_pct": 1.4, + "oi_change_4h_pct": 5.5, + }, + "ohlcv": { + "15m": [{"close": 100.0}, {"close": 101.5}], + "1h": [{"close": 99.0}, {"close": 101.5}], + "4h": [{"close": 95.0}, {"close": 96.0}, {"close": 97.0}, {"close": 98.0}, {"close": 101.5}], + }, + } + oi_res = _compute_oi_divergence(b_oi, None, None, None) + assert oi_res["intraday_score"] == -1 + assert oi_res["swing_score"] == 1 + + +def test_ai_prompt_handles_none_whale_fields_and_exposes_multilayer_metrics(): + """_build_ai_prompt safely handles None values in whale_flow without 0.0% hallucination.""" + from routers.ai import _build_ai_prompt + + signal = { + "conviction": 5, + "direction": "LONG", + "signal_data": { + "whale_flow": { + "taker_buy_pct": None, + "taker_ratio": None, + "twap_bias": "WHALE_TWAP_LONG_BUILDUP", + "twap_buy_pct": None, + "absorption_type": "NONE", + "whale_position_long_ratio": None, + "retail_account_long_ratio": None, + "smart_money_delta": None, + "onchain_whale_wallets": 2, + "flow_verdict": "Akumulasi TWAP Paus", + }, + "signals": { + "oi_divergence": { + "score": 1, + "label": "Bullish OI Buildup", + "direction_val": "Price Up + OI Up", + "oi_change_1h_pct": 1.4, + "oi_change_4h_pct": 5.5, + }, + "fake_detector": { + "is_fake": True, + "warnings": ["Wick sweep detected"], + }, + }, + }, + } + prompt, summary = _build_ai_prompt("BTCUSDT", signal, [{"exchange": "binance", "mark_price": 65000.0}]) + assert "Whale Pos Long: N/A vs Retail Long: N/A (Delta: N/A)" in prompt + assert "Whale Pos Long: 0.0%" not in prompt + assert "Absorption: Tidak ada" in prompt + assert "1H OI: +1.40% | 4H OI: +5.50%" in prompt + assert "Wick sweep detected" in prompt + assert summary["twap_bias"] == "WHALE_TWAP_LONG_BUILDUP" + assert summary["oi_change_4h_pct"] == 5.5 + assert summary["onchain_whale_wallets"] == 2 + + +def test_rolling_oi_snapshot_preserves_window_across_rapid_polls(monkeypatch): + """BaseExchange._record_oi_change retains an older baseline instead of collapsing to 0% on rapid polls.""" + from exchanges.okx import OKXClient + + client = OKXClient() + fake_now = [1000.0] + monkeypatch.setattr("exchanges.base.time.time", lambda: fake_now[0]) + + # Initial reading seeds history + assert client._record_oi_change("BTC-USDT-SWAP", 1000.0) is None + # 60s later OI rises 2% + fake_now[0] = 1060.0 + assert client._record_oi_change("BTC-USDT-SWAP", 1020.0) == pytest.approx(2.0) + # 5s later (rapid duplicate poll) OI is unchanged -> must NOT reset delta to 0.0% + fake_now[0] = 1065.0 + assert client._record_oi_change("BTC-USDT-SWAP", 1020.0) == pytest.approx(2.0) + # 365s total elapsed (> 300s window from 1060s baseline after waiting): at t=1365, anchor is t=1060 (1020.0) + fake_now[0] = 1365.0 + assert client._record_oi_change("BTC-USDT-SWAP", 1071.0) == pytest.approx(5.0) + + + +