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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
"""
Empirical Factor Calibration & Continuous Microstructure Tape Engine.

Provides:
1. Continuous 15m/5m tape recording with strict throttling (max 1 row / 5 min / symbol).
2. Forward return resolution (+15m, +1h, +4h) across recorded market states.
3. Empirical Factor Hit-Rate Matrix & Information Coefficient (IC) evaluation.
4. Objective Data-Driven Whale Threshold Calibrator (sweeping 1.4x, 0.06, ADV floors).
"""

from __future__ import annotations

import copy
import logging
import math
import time
from datetime import datetime, timezone
from typing import Any

from database.db import (
    db_insert_microstructure_tape,
    db_get_microstructure_tape,
    db_get_unevaluated_microstructure_tape,
    db_update_microstructure_tape_returns,
)

logger = logging.getLogger(__name__)

# In-memory throttle tracker: symbol -> last_recorded_timestamp_ms
_LAST_TAPE_WRITE_MS: dict[str, int] = {}
THROTTLE_MS = 300_000  # 5 minutes


def should_record_tape(symbol: str, now_ms: int | None = None) -> bool:
    """Check if 5 minutes have elapsed since the last tape write for this symbol."""
    curr_ms = now_ms or int(time.time() * 1000)
    last_ms = _LAST_TAPE_WRITE_MS.get(symbol.upper(), 0)
    return (curr_ms - last_ms) >= THROTTLE_MS


def record_microstructure_tape_slice(
    symbol: str,
    signal_dict: dict[str, Any],
    exchange_data: dict[str, Any] | None = None,
    now_ms: int | None = None,
    force: bool = False,
) -> dict[str, Any] | None:
    """
    Capture a compact causal snapshot of microstructure telemetry.
    Throttled to at most 1 write per symbol every 5 minutes.
    """
    sym = symbol.upper()
    curr_ms = now_ms or int(time.time() * 1000)
    if not force and not should_record_tape(sym, curr_ms):
        return None

    mark_px = float(
        signal_dict.get("price_extremes", {}).get("mark_price")
        or signal_dict.get("trade_levels", {}).get("entry")
        or 0.0
    )
    if mark_px <= 0 and exchange_data:
        for ex in exchange_data.values():
            if isinstance(ex, dict) and ex.get("mark_price_data"):
                try:
                    mark_px = float(ex["mark_price_data"].get("mark_price") or 0.0)
                    if mark_px > 0:
                        break
                except (ValueError, TypeError):
                    pass

    adv_24h = float(signal_dict.get("adv_24h_usd", 0.0) or 0.0)

    # 1. Horizon Scores
    horizons = signal_dict.get("horizons") or {}
    horizon_scores = {
        "intraday_score": (horizons.get("intraday") or {}).get("score"),
        "intraday_direction": (horizons.get("intraday") or {}).get("direction"),
        "swing_score": (horizons.get("swing") or {}).get("score"),
        "swing_direction": (horizons.get("swing") or {}).get("direction"),
        "primary_score": signal_dict.get("score"),
        "primary_direction": signal_dict.get("direction"),
    }

    # 2. Factor Scores
    sig_map = signal_dict.get("signals") or {}
    factor_scores: dict[str, int] = {}
    for f_name, f_data in sig_map.items():
        if isinstance(f_data, dict) and "score" in f_data:
            try:
                factor_scores[f_name] = int(f_data.get("score", 0) or 0)
            except (ValueError, TypeError):
                factor_scores[f_name] = 0

    # 3. Quantitative Whale Sub-Metrics (for zero-latency hyperparameter sweeps)
    wf = signal_dict.get("whale_flow") or {}
    liq_c = signal_dict.get("liquidation_cascade") or {}
    l2_m = signal_dict.get("l2_microstructure") or {}

    twap_delta_ratio = float(wf.get("twap_delta_ratio", 0.0) or 0.0)
    twap_tot_usd = float(wf.get("twap_tot_usd", 0.0) or 0.0)
    if twap_tot_usd <= 0 and abs(twap_delta_ratio) > 1e-9:
        twap_net_delta = float(wf.get("twap_net_delta_usd", 0.0) or 0.0)
        if twap_net_delta != 0.0:
            twap_tot_usd = abs(twap_net_delta) / abs(twap_delta_ratio)

    whale_sub_metrics = {
        "whale_buy_vol_usd": float(wf.get("whale_buy_vol_usd", 0.0) or 0.0),
        "whale_sell_vol_usd": float(wf.get("whale_sell_vol_usd", 0.0) or 0.0),
        "sweep_buy_vol_usd": float(wf.get("sweep_buy_vol_usd", 0.0) or 0.0),
        "sweep_sell_vol_usd": float(wf.get("sweep_sell_vol_usd", 0.0) or 0.0),
        "sweep_buy_count": int(wf.get("sweep_buy_count", 0) or 0),
        "sweep_sell_count": int(wf.get("sweep_sell_count", 0) or 0),
        "twap_delta_ratio": twap_delta_ratio,
        "twap_tot_usd": twap_tot_usd,
        "dynamic_threshold_usd": float(wf.get("dynamic_threshold_usd", 25000.0) or 25000.0),
        "adv_floor_usd": float(wf.get("adv_floor_usd", 5000.0) or 5000.0),
        "long_liq_usd": float(liq_c.get("long_liq_usd", 0.0) or 0.0),
        "short_liq_usd": float(liq_c.get("short_liq_usd", 0.0) or 0.0),
        "l2_iceberg_score": int(l2_m.get("l2_iceberg_score", 0) or 0),
        "block_score": int(wf.get("whale_block_score", 0) or 0),
        "twap_score": int(wf.get("twap_score", 0) or 0),
        "absorption_score": int(wf.get("absorption_score", 0) or 0),
        "onchain_score": int(wf.get("onchain_score", 0) or 0),
    }

    # 4. Compact Raw Replay Slice (under 4 KB)
    compact_trades: list[dict] = []
    if exchange_data:
        all_raw_trades: list[dict] = []
        for v_name, v_data in exchange_data.items():
            if isinstance(v_data, dict) and v_data.get("trades"):
                for t in v_data["trades"][-50:]:
                    is_sell_t = bool(t.get("is_buyer_maker", False)) or str(t.get("side", "")).upper().startswith("S")
                    all_raw_trades.append({
                        "p": float(t.get("price") or 0.0),
                        "q": float(t.get("qty") or 0.0),
                        "s": "S" if is_sell_t else "B",
                        "v": v_name[:2],
                    })
        # Keep top 30 largest notional trades in window
        all_raw_trades.sort(key=lambda x: x["p"] * x["q"], reverse=True)
        compact_trades = all_raw_trades[:30]

    raw_replay_slice = {
        "top_trades": compact_trades,
        "hl_whale_bias": signal_dict.get("hl_whale_summary", {}).get("smart_bias", "NEUTRAL"),
        "spoof_pulled": bool(l2_m.get("spoof_pulled", False)),
    }

    row_data = {
        "symbol": sym,
        "timestamp_ms": curr_ms,
        "mark_price": mark_px,
        "adv_24h_usd": adv_24h,
        "horizon_scores": horizon_scores,
        "factor_scores": factor_scores,
        "whale_sub_metrics": whale_sub_metrics,
        "raw_replay_slice": raw_replay_slice,
    }

    try:
        saved = db_insert_microstructure_tape(row_data)
        _LAST_TAPE_WRITE_MS[sym] = curr_ms
        return saved
    except Exception as exc:
        logger.warning("[Tape Engine] Failed to record tape slice for %s: %s", sym, exc)
        return None


def resolve_tape_forward_returns(
    tape_row: dict[str, Any],
    subsequent_candles_15m: list[dict[str, Any]],
) -> tuple[float | None, float | None, float | None]:
    """
    Given a tape entry at timestamp_ms and mark_price, calculate:
    - ret_15m_pct: return after 15 minutes (index +1 on 15m)
    - ret_1h_pct: return after 60 minutes (index +4 on 15m)
    - ret_4h_pct: return after 240 minutes (index +16 on 15m)
    """
    mark_px = float(tape_row.get("mark_price", 0.0) or 0.0)
    if mark_px <= 0 or not subsequent_candles_15m:
        return None, None, None

    sorted_candles = sorted(
        subsequent_candles_15m,
        key=lambda c: int(c.get("timestamp") or c.get("time") or 0),
    )

    t_ms = int(tape_row.get("timestamp_ms") or 0)
    ret_15m = None
    ret_1h = None
    ret_4h = None

    for c in sorted_candles:
        c_ts = int(c.get("timestamp") or c.get("time") or 0)
        c_close = float(c.get("close") or 0.0)
        if c_ts <= t_ms or c_close <= 0:
            continue

        delta_min = (c_ts - t_ms) / 60_000.0

        if ret_15m is None and 10.0 <= delta_min <= 25.0:
            ret_15m = round(((c_close - mark_px) / mark_px) * 100.0, 3)

        if ret_1h is None and 50.0 <= delta_min <= 75.0:
            ret_1h = round(((c_close - mark_px) / mark_px) * 100.0, 3)

        if ret_4h is None and 220.0 <= delta_min <= 265.0:
            ret_4h = round(((c_close - mark_px) / mark_px) * 100.0, 3)
            break

    return ret_15m, ret_1h, ret_4h


def async_evaluate_microstructure_tape(
    candles_by_symbol: dict[str, list[dict[str, Any]]],
    limit: int = 200,
) -> int:
    """
    Evaluates unevaluated tape entries against subsequent 15m candle closes.
    Returns the number of resolved rows.
    """
    unevaluated = db_get_unevaluated_microstructure_tape(limit=limit)
    if not unevaluated:
        return 0

    evaluated_count = 0
    for r in unevaluated:
        sym = str(r.get("symbol", "")).upper()
        candles = candles_by_symbol.get(sym) or []
        if not candles:
            continue

        r15, r1h, r4h = resolve_tape_forward_returns(r, candles)
        if r15 is not None or r1h is not None or r4h is not None:
            tape_id = int(r.get("id") or 0)
            if tape_id > 0:
                db_update_microstructure_tape_returns(tape_id, r15, r1h, r4h)
                evaluated_count += 1

    return evaluated_count


def compute_factor_calibration_report(
    tape_rows: list[dict[str, Any]],
    symbol: str | None = None,
) -> dict[str, Any]:
    """
    Empirical Factor Hit-Rate Matrix & Information Coefficient (IC) evaluation.
    Computes hit rates and average directional returns for each factor across
    15m, 1h, and 4h horizons.
    """
    target_rows = [
        r for r in tape_rows
        if (not symbol or r.get("symbol") == symbol.upper())
        and (r.get("ret_15m_pct") is not None or r.get("ret_1h_pct") is not None or r.get("ret_4h_pct") is not None)
    ]

    total_samples = len(target_rows)
    if total_samples == 0:
        return {
            "status": "NO_EVALUATED_DATA",
            "total_evaluated_samples": 0,
            "symbol": symbol,
            "factors": {},
            "top_performing_factors": [],
            "low_hit_rate_factors": [],
        }

    # Factor accumulator
    factors: dict[str, dict[str, Any]] = {}

    all_factor_names = [
        "whale_order_flow",
        "liquidation_cascade",
        "spot_futures_cvd",
        "oi_divergence",
        "funding_rate",
        "ls_ratio",
        "hyperliquid",
        "orderbook_skew",
        "market_structure",
        "cvd",
    ]

    for fname in all_factor_names:
        horizons_stats: dict[str, dict[str, Any]] = {}
        for h_key in ("ret_15m_pct", "ret_1h_pct", "ret_4h_pct"):
            aligned_returns: list[float] = []
            scores: list[int] = []
            raw_returns: list[float] = []

            for r in target_rows:
                ret = r.get(h_key)
                if ret is None:
                    continue
                f_scores = r.get("factor_scores") or {}
                sc = int(f_scores.get(fname, 0) or 0)
                if sc == 0:
                    continue

                dir_mult = 1.0 if sc > 0 else -1.0
                aligned_returns.append(float(ret) * dir_mult)
                scores.append(sc)
                raw_returns.append(float(ret))

            n = len(aligned_returns)
            if n > 0:
                wins = sum(1 for ret in aligned_returns if ret > 0)
                hit_rate = round((wins / n) * 100.0, 1)
                avg_dir_ret = round(sum(aligned_returns) / n, 3)

                # Linear correlation / IC approximation
                ic = 0.0
                mean_s = sum(scores) / n
                mean_r = sum(raw_returns) / n
                num = sum((scores[i] - mean_s) * (raw_returns[i] - mean_r) for i in range(n))
                den_s = math.sqrt(sum((scores[i] - mean_s) ** 2 for i in range(n)))
                den_r = math.sqrt(sum((raw_returns[i] - mean_r) ** 2 for i in range(n)))
                if den_s > 0 and den_r > 0:
                    ic = round(num / (den_s * den_r), 3)

                horizons_stats[h_key] = {
                    "sample_count": n,
                    "hit_rate_pct": hit_rate,
                    "avg_directional_return_pct": avg_dir_ret,
                    "information_coefficient": ic,
                }
            else:
                horizons_stats[h_key] = {
                    "sample_count": 0,
                    "hit_rate_pct": 50.0,
                    "avg_directional_return_pct": 0.0,
                    "information_coefficient": 0.0,
                }

        factors[fname] = horizons_stats

    # Rank factors by 1H hit rate & directional return
    ranked = sorted(
        factors.keys(),
        key=lambda fn: (
            factors[fn].get("ret_1h_pct", {}).get("hit_rate_pct", 50.0),
            factors[fn].get("ret_1h_pct", {}).get("avg_directional_return_pct", 0.0),
        ),
        reverse=True,
    )

    top_factors = [
        f"{fn} ({factors[fn]['ret_1h_pct']['hit_rate_pct']}% 1H Hit-Rate, +{factors[fn]['ret_1h_pct']['avg_directional_return_pct']}%)"
        for fn in ranked[:3]
        if factors[fn]["ret_1h_pct"]["sample_count"] >= 3
    ]

    low_factors = [
        f"{fn} ({factors[fn]['ret_1h_pct']['hit_rate_pct']}% 1H Hit-Rate)"
        for fn in reversed(ranked)
        if factors[fn]["ret_1h_pct"]["sample_count"] >= 3 and factors[fn]["ret_1h_pct"]["hit_rate_pct"] < 50.0
    ]

    return {
        "status": "CALIBRATED",
        "total_evaluated_samples": total_samples,
        "symbol": symbol,
        "factors": factors,
        "top_performing_factors": top_factors,
        "low_hit_rate_factors": low_factors,
    }


def calibrate_whale_thresholds(tape_rows: list[dict[str, Any]]) -> dict[str, Any]:
    """
    Data-Driven Threshold Calibrator:
    Sweeps candidate hyperparameters over recorded whale_sub_metrics rows
    to maximize directional expectancy:
    `expectancy = mean_directional_return_1h * sqrt(hit_rate)`.
    """
    evaluated = [
        r for r in tape_rows
        if r.get("ret_1h_pct") is not None and isinstance(r.get("whale_sub_metrics"), dict)
    ]

    if len(evaluated) < 10:
        return {
            "status": "INSUFFICIENT_SAMPLES",
            "samples_count": len(evaluated),
            "min_required": 10,
            "optimal_thresholds": {
                "block_dominance_mult": 1.4,
                "twap_delta_min": 0.06,
                "twap_notional_min_usd": 25_000.0,
            },
            "message": "Samples < 10; maintaining robust institutional default thresholds.",
        }

    # Grid search candidate tuples
    mult_candidates = [1.2, 1.4, 1.6, 1.8, 2.0]
    delta_candidates = [0.04, 0.06, 0.08, 0.10]
    notional_candidates = [15_000.0, 25_000.0, 50_000.0]

    best_expectancy = -999.0
    best_params = (1.4, 0.06, 25_000.0)
    best_stats: dict[str, Any] = {}

    for mult in mult_candidates:
        for delta_min in delta_candidates:
            for notional_min in notional_candidates:
                aligned_returns: list[float] = []
                for r in evaluated:
                    m = r["whale_sub_metrics"]
                    w_buy = float(m.get("whale_buy_vol_usd", 0.0) or 0.0)
                    w_sell = float(m.get("whale_sell_vol_usd", 0.0) or 0.0)
                    twap_delta = float(m.get("twap_delta_ratio", 0.0) or 0.0)
                    twap_tot = float(m.get("twap_tot_usd", 0.0) or 0.0)
                    ret_1h = float(r["ret_1h_pct"])

                    sim_score = 0
                    if w_buy > w_sell * mult and w_buy >= notional_min:
                        sim_score = 1
                    elif w_sell > w_buy * mult and w_sell >= notional_min:
                        sim_score = -1
                    elif twap_tot >= notional_min:
                        if twap_delta >= delta_min:
                            sim_score = 1
                        elif twap_delta <= -delta_min:
                            sim_score = -1

                    if sim_score != 0:
                        aligned_returns.append(ret_1h * (1.0 if sim_score > 0 else -1.0))

                if len(aligned_returns) >= 5:
                    n = len(aligned_returns)
                    wins = sum(1 for ret in aligned_returns if ret > 0)
                    hit_rate = (wins / n) * 100.0
                    mean_ret = sum(aligned_returns) / n
                    if mean_ret > 0:
                        expectancy = mean_ret * math.sqrt(hit_rate)
                    else:
                        expectancy = mean_ret / max(math.sqrt(max(hit_rate, 1.0)), 1.0)

                    if expectancy > best_expectancy:
                        best_expectancy = expectancy
                        best_params = (mult, delta_min, notional_min)
                        best_stats = {
                            "samples": n,
                            "hit_rate_pct": round(hit_rate, 1),
                            "avg_return_1h_pct": round(mean_ret, 3),
                            "expectancy": round(expectancy, 3),
                        }

    return {
        "status": "OPTIMIZED",
        "samples_count": len(evaluated),
        "optimal_thresholds": {
            "block_dominance_mult": best_params[0],
            "twap_delta_min": best_params[1],
            "twap_notional_min_usd": best_params[2],
        },
        "performance": best_stats,
    }