-- 0003_market_snapshots.sql — periodic market snapshot table.
--
-- Populated by the `market_snapshot` scheduler job (cron */15) for
-- every asset traded by the engine (ETH primary, BTC as benchmark).
-- The table backs the "Calibrazione" GUI page: histograms, percentiles
-- and "% of ticks the current threshold would have blocked" let the
-- operator pick filter thresholds from observed distributions instead
-- of guessing.
--
-- Every column except (timestamp, asset, fetch_ok) is NULL-able: a
-- single MCP call may fail and we still want to keep the row so the
-- time series stays continuous. fetch_errors_json carries the per-feed
-- error messages for offline debugging.

CREATE TABLE market_snapshots (
    timestamp                  TEXT    NOT NULL,
    asset                      TEXT    NOT NULL,
    spot                       NUMERIC,
    dvol                       NUMERIC,
    realized_vol_30d           NUMERIC,
    iv_minus_rv                NUMERIC,
    funding_perp_annualized    NUMERIC,
    funding_cross_annualized   NUMERIC,
    dealer_net_gamma           NUMERIC,
    gamma_flip_level           NUMERIC,
    oi_delta_pct_4h            NUMERIC,
    liquidation_long_risk      TEXT,
    liquidation_short_risk     TEXT,
    macro_days_to_event        INTEGER,
    fetch_ok                   INTEGER NOT NULL,
    fetch_errors_json          TEXT,
    PRIMARY KEY (timestamp, asset)
);

CREATE INDEX idx_market_snapshots_asset_ts
    ON market_snapshots(asset, timestamp DESC);

PRAGMA user_version = 3;
