{
  "key": "f-cancel-option",
  "approach": "Cancellation option pricing around one opaque N instance. Each callback calls N first. A moment filter estimates p using competitor quote bounds, surviving own orders and aggregate fill evidence; a diffusion/jump Gaussian mixture supplies a clipped one-step predictive. For each quote, compare remaining quantity times 0.25 times the expected adverse payoff with one step of lognormal retail fill income plus an estimated FIFO retention credit. Cancel unsafe surviving N orders and suppress unsafe N placements; admit N re-quotes when their estimated sign turns favorable. No independent orders are added, so there are no overlay orders to hide. The frozen gate acts only at first-step spread s in [1]; all other runs return N's actions unchanged.",
  "tried": {
    "incumbent_sha256": "bf0d179f3e47d28819f6fa7e0d25548c2ced43374c216d36460b00a26a26ffae",
    "baseline_check": {
      "seed": 310000,
      "edge": 17.1160017503,
      "expected_rounded": 17.116002,
      "matched": true
    },
    "protocol": {
      "simulator_commit": "b244530ee2a6247b5f930830eeca9dd950da0e7e",
      "configuration": "Unmodified ChallengeConfig() and ParameterVariance(); 2000 steps; serial in-process SimulationEngine; no workers or sandbox.",
      "tuning_seeds": [
        310000,
        310199
      ],
      "holdout_seeds": [
        410000,
        410499
      ],
      "finalist_seeds_run": 0,
      "simulator_files_verified_unmodified": 19
    },
    "variants": [
      {
        "variant": "full",
        "option_cost_weight": 1.0,
        "all_spreads_tuning": {
          "n": 200,
          "mean_diff": -50.729827103422004,
          "se": 6.517824252116895,
          "retail_diff": -57.7028999848455,
          "arb_diff": 6.973072881365
        },
        "by_spread_tuning": {
          "1": {
            "n": 47,
            "mean_diff": -25.273415109346807,
            "se": 7.566122197928496
          },
          "2": {
            "n": 57,
            "mean_diff": -60.03760222595438,
            "se": 12.672399631155624
          },
          "3": {
            "n": 53,
            "mean_diff": -73.82695854006415,
            "se": 17.311055018990793
          },
          "4": {
            "n": 43,
            "mean_diff": -37.747506535867444,
            "se": 9.341598001141758
          }
        }
      },
      {
        "variant": "quarter",
        "option_cost_weight": 0.25,
        "all_spreads_tuning": {
          "n": 200,
          "mean_diff": -45.257612326725,
          "se": 5.818127175835648,
          "retail_diff": -36.473359298436,
          "arb_diff": -8.7842530283735
        },
        "by_spread_tuning": {
          "1": {
            "n": 47,
            "mean_diff": -25.070782426874466,
            "se": 7.302125038091416
          },
          "2": {
            "n": 57,
            "mean_diff": -57.18739027004561,
            "se": 12.386992629099309
          },
          "3": {
            "n": 53,
            "mean_diff": -58.68118580845661,
            "se": 14.486956266086198
          },
          "4": {
            "n": 43,
            "mean_diff": -34.96306041956046,
            "se": 8.23323800238771
          }
        }
      }
    ],
    "selection": "Exactly two strengths were evaluated on all 200 tuning seeds. Choose the highest paired tuning mean over those strengths and nonempty spread subsets, using exact zero differences on inactive spreads. No holdout data entered selection.",
    "selected_variant": "quarter",
    "frozen_at_utc": "2026-11-06T20:15:27Z",
    "checks": {
      "off_seeds": [
        310000,
        310001,
        310002,
        310003,
        310004,
        310005,
        310006,
        310007,
        310008,
        310009
      ],
      "off_comparison": "Exact callback state/action trace hashes and full SimulationResult equality over 2000 steps.",
      "assembled_seeds": [
        310002,
        310005,
        310011,
        310000,
        310001
      ],
      "assembled_equals_s1": true,
      "assembled_matches_tuning": true,
      "gate_checks": [
        "unsafe placement suppressed",
        "safe re-entry admitted",
        "unsafe resting order cancelled",
        "no double cancellation",
        "cancel of suppressed new order removed",
        "CancelAll preserved",
        "inactive spread exact passthrough",
        "off exact passthrough",
        "N called every callback"
      ],
      "option_integration": {
        "passed": true,
        "max_absolute_error": 1.723807867282101e-10
      },
      "inactive_holdout_results_equal": true
    },
    "limits": "The predictive is approximate, not the simulator true probability. Retail flow is shrunk toward randomized-parameter priors. Queue priority is inferred from best-quote history and credited for four steps; hidden queue size is not observed. Re-entry requires N to propose the quote again. Cancellation also changes N's later observations; paired scores include that feedback."
  },
  "next": "Do not promote this overlay. The frozen holdout does not support improvement over N. Any further probability or queue-model work requires a new tuning allocation; no third variant or holdout-driven change was tried.",
  "spreads_acted": [
    1
  ],
  "off_equals_n": true,
  "code": "import math as _co_m\nfrom statistics import NormalDist as _CONormal\nfrom orderbook_pm_challenge.strategy import BaseStrategy as _COBase\nfrom orderbook_pm_challenge.types import (\n    PlaceOrder as _COPlace, CancelOrder as _COCancel,\n    CancelAll as _COAll, Side as _COSide,\n)\n\n\nclass Strategy(_COBase):\n    def __init__(self, enabled=True, spreads=(1,), option_weight=0.25):\n        self.n = _N()\n        self.enabled = enabled\n        self.spreads = frozenset(spreads)\n        self.option_weight = option_weight\n        self.spread = None\n        self.mean = 0.5\n        self.var = 1e-5\n        self.pred = None\n        self.last = []\n        self.last_comp = (0, 100)\n        self.last_mean = 0.5\n        self.flow_sum = 100.0 * 0.1265 * 4.488\n        self.exposures = 100.0\n        self.birth = {}\n        self.quotes = (None, None)\n\n    @staticmethod\n    def _cdf(x):\n        return 0.5 * _co_m.erfc(-x / 1.4142135623730951)\n\n    @staticmethod\n    def _pdf(x):\n        return 0.3989422804014327 * _co_m.exp(-0.5 * x * x)\n\n    @classmethod\n    def _moments(cls, mu, sd, lo, hi):\n        a, b = (lo - mu) / sd, (hi - mu) / sd\n        if a > 0:\n            mass = cls._cdf(-a) - cls._cdf(-b)\n        else:\n            mass = cls._cdf(b) - cls._cdf(a)\n        if mass < 1e-18:\n            return 0.0, 0.0, 0.0\n        pa, pb = cls._pdf(a), cls._pdf(b)\n        delta = pa - pb\n        return (mass, mu * mass + sd * delta,\n                (mu * mu + sd * sd) * mass + 2 * mu * sd * delta\n                + sd * sd * (a * pa - b * pb))\n\n    @classmethod\n    def _stoploss(cls, strike, mean):\n        if strike <= 1e-12:\n            return mean\n        z = (_co_m.log(mean / strike) - 0.72) / 1.2\n        return max(0.0, mean * cls._cdf(z + 1.2) - strike * cls._cdf(z))\n\n    def _learn(self, state):\n        b = state.competitor_best_bid_ticks\n        a = state.competitor_best_ask_ticks\n        quotes = (b, a)\n        for side, tick, old in zip((_COSide.BUY, _COSide.SELL), quotes, self.quotes):\n            if tick is not None and tick != old:\n                self.birth[side, tick] = state.step\n        self.quotes = quotes\n        b, a = (b if b is not None else 0), (a if a is not None else 100)\n        if self.pred is None:\n            self.mean = (b + a) * 0.005\n            self.var = 0.0001 / 12\n        else:\n            lo, hi = b * 0.01 - 0.001, a * 0.01 + 0.001\n            for o in state.own_orders:\n                if o.side == _COSide.BUY:\n                    lo = max(lo, o.price_ticks * 0.01)\n                else:\n                    hi = min(hi, o.price_ticks * 0.01)\n            lo, hi = max(0.0, lo), min(1.0, hi)\n            if lo >= hi:\n                lo, hi = max(0.0, min(lo, hi) - 0.005), min(1.0, max(lo, hi) + 0.005)\n            evidence = []\n            for side, filled, comp in (\n                (_COSide.BUY, state.buy_filled_quantity, self.last_comp[0]),\n                (_COSide.SELL, state.sell_filled_quantity, self.last_comp[1]),\n            ):\n                prev = [x for x in self.last if x[0] == side]\n                if not prev:\n                    continue\n                tick = (max if side == _COSide.BUY else min)(x[1] for x in prev)\n                qty = sum(x[2] for x in prev if x[1] == tick)\n                conv = max(self.last_mean, 0.05) if side == _COSide.BUY else tick * 0.01\n                ahead = tick > comp if side == _COSide.BUY else tick < comp\n                if ahead and qty * conv >= 15 and filled < qty - 0.005:\n                    self.flow_sum += filled * conv\n                    self.exposures += 1\n                if filled >= qty - 0.005 and qty > 0:\n                    survives = any(o.side == side and o.price_ticks == tick for o in state.own_orders)\n                    if not survives:\n                        mean_size = self._flow() / 0.1265\n                        cash = max(0.01, qty * conv)\n                        z = (_co_m.log(cash / mean_size) + 0.72) / 1.2\n                        retail_prob = min(0.25, max(0.003, 0.1265 * self._cdf(-z)))\n                        evidence.append((side, tick * 0.01, retail_prob))\n            cuts = sorted(set([lo, hi] + [x[1] for x in evidence if lo < x[1] < hi]))\n            total = first = second = 0.0\n            for left, right in zip(cuts, cuts[1:]):\n                midpoint = (left + right) * 0.5\n                likelihood = 1.0\n                for side, strike, retail_prob in evidence:\n                    adverse = midpoint < strike if side == _COSide.BUY else midpoint > strike\n                    if not adverse:\n                        likelihood *= retail_prob\n                for weight, mu, sd in self.pred:\n                    mass, m1, m2 = self._moments(mu, sd, left, right)\n                    w = weight * likelihood\n                    total += w * mass\n                    first += w * m1\n                    second += w * m2\n            if total > 1e-15:\n                self.mean = first / total\n                self.var = max(1e-8, second / total - self.mean * self.mean)\n            else:\n                self.mean, self.var = (lo + hi) * 0.5, (hi - lo) ** 2 / 12\n        self.mean = min(0.9999, max(0.0001, self.mean))\n        h = max(1, state.steps_remaining)\n        z = _CONormal().inv_cdf(self.mean)\n        sensitivity = self._pdf(z) / _co_m.sqrt(0.0007293 * h)\n        diffusion = max(0.0002, 0.02 * sensitivity)\n        jump = max(diffusion, 0.40 * sensitivity)\n        self.pred = ((0.9981, self.mean, _co_m.sqrt(self.var + diffusion ** 2)),\n                     (0.0019, self.mean, _co_m.sqrt(self.var + jump ** 2)))\n        self.last_mean, self.last_comp = self.mean, (b, a)\n\n    def _flow(self):\n        return min(1.115136, max(0.20328, self.flow_sum / self.exposures))\n\n    def _positive(self, strike, call):\n        result = 0.0\n        for weight, mu, sd in self.pred:\n            d = (mu - strike) if call else (strike - mu)\n            z = d / sd\n            value = sd * self._pdf(z) + d * self._cdf(z)\n            boundary = (mu - 1.0) if call else -mu\n            bz = boundary / sd\n            value -= sd * self._pdf(bz) + boundary * self._cdf(bz)\n            result += weight * max(0.0, value)\n        return result\n\n    def _unsafe(self, side, tick, qty, submitted, others):\n        price = tick * 0.01\n        buy = side == _COSide.BUY\n        cost = qty * self._positive(price, not buy) * self.option_weight\n        if cost <= 1e-10:\n            return False\n        favorable = self._positive(price, buy)\n        comp = self.last_comp[0 if buy else 1]\n        levels = max(0, comp - tick + 1) if buy else max(0, tick - comp + 1)\n        fifo_ahead = (tick == comp and submitted < self.birth.get((side, tick), -1))\n        if fifo_ahead:\n            levels = 0\n        conv = max(self.mean, 0.05) if buy else price\n        queue_cash = levels * 48.0 * (conv / max(price, 0.01) if buy else 1.0)\n        for oside, otick, oqty, otime in others:\n            better = otick > tick if buy else otick < tick\n            if oside == side and (better or (otick == tick and otime < submitted)):\n                queue_cash += oqty * conv\n        mean_size = self._flow() / 0.1265\n        def fills(ahead):\n            return 0.1265 * max(0.0, self._stoploss(ahead, mean_size)\n                               - self._stoploss(ahead + qty * conv, mean_size)) / conv\n        expected_fill = fills(queue_cash)\n        income = expected_fill * favorable\n        lost_queue = 0.0\n        if fifo_ahead:\n            replacement_queue = queue_cash + 48.0 * conv / max(price, 0.01)\n            lost_queue = 4.0 * max(0.0, expected_fill - fills(replacement_queue)) * favorable\n        return cost > income + lost_queue\n\n    def on_step(self, state):\n        if self.spread is None:\n            b, a = state.competitor_best_bid_ticks, state.competitor_best_ask_ticks\n            self.spread = max(1, (a - b + 1) // 2) if b is not None and a is not None else 0\n        actions = self.n.on_step(state)\n        if not self.enabled or self.spread not in self.spreads:\n            return actions\n        self._learn(state)\n        actions = list(actions)\n        cancelled = {a.order_id for a in actions if isinstance(a, _COCancel)}\n        all_cancelled = any(isinstance(a, _COAll) for a in actions)\n        active = {o.order_id: (o.side, o.price_ticks, o.remaining_quantity, o.submitted_step)\n                  for o in state.own_orders}\n        out = []\n        if not all_cancelled:\n            for o in state.own_orders:\n                if o.order_id not in cancelled:\n                    other = [v for k, v in active.items() if k != o.order_id and k not in cancelled]\n                    if self._unsafe(o.side, o.price_ticks, o.remaining_quantity,\n                                    o.submitted_step, other):\n                        out.append(_COCancel(o.order_id))\n                        active.pop(o.order_id, None)\n        suppressed = set()\n        for i, action in enumerate(actions):\n            if isinstance(action, _COAll):\n                active.clear()\n                suppressed.clear()\n                out.append(action)\n            elif isinstance(action, _COCancel):\n                active.pop(action.order_id, None)\n                if action.order_id not in suppressed:\n                    out.append(action)\n                suppressed.discard(action.order_id)\n            elif isinstance(action, _COPlace):\n                oid = action.client_order_id or ('pending', i)\n                qty = _co_m.floor(float(action.quantity) * 100 + 1e-8) / 100\n                if self._unsafe(action.side, action.price_ticks, qty, state.step, list(active.values())):\n                    suppressed.add(oid)\n                else:\n                    active[oid] = (action.side, action.price_ticks, qty, state.step)\n                    out.append(action)\n                    suppressed.discard(oid)\n            else:\n                out.append(action)\n        self.last = list(active.values())\n        return out\n",
  "code_sha256": "6a1180ff62873ae5d0c5ab61af4a05383e107744812c38b29cfb496d63d88f14",
  "assembled_sha256": "a3a91fc9cc756f0843db5ffcb262e37523e032c8b31fdda0df32fea7e9a850d3",
  "tuning": {
    "n": 200,
    "mean_diff": -5.891633870315499,
    "se": 1.8612645729822324
  },
  "paired": {
    "first_seed": 410000,
    "last_seed": 410499,
    "n": 500,
    "complete": true,
    "incumbent_mean": 104.4137531881468,
    "mean_diff": -5.220709118934,
    "se": 1.4712629988686723,
    "sum_d": -2610.354559467,
    "sum_d2": 553699.29740635,
    "retail_diff": -8.0537476222348,
    "arb_diff": 2.8330385032884,
    "failures": 0
  },
  "by_spread": {
    "1": {
      "runs": 115,
      "incumbent_mean": 28.495154459731307,
      "mean_diff": -22.698735299713043,
      "se": 6.141278164992826,
      "sum_d": -2610.354559467,
      "sum_d2": 553699.29740635,
      "retail_diff": -35.01629400971652,
      "arb_diff": 12.317558709949566
    },
    "2": {
      "runs": 116,
      "incumbent_mean": 97.76626247947758,
      "mean_diff": 0.0,
      "se": 0.0,
      "sum_d": 0.0,
      "sum_d2": 0.0,
      "retail_diff": 0.0,
      "arb_diff": 0.0
    },
    "3": {
      "runs": 138,
      "incumbent_mean": 128.4054514027384,
      "mean_diff": 0.0,
      "se": 0.0,
      "sum_d": 0.0,
      "sum_d2": 0.0,
      "retail_diff": 0.0,
      "arb_diff": 0.0
    },
    "4": {
      "runs": 131,
      "incumbent_mean": 151.67248160310686,
      "mean_diff": 0.0,
      "se": 0.0,
      "sum_d": 0.0,
      "sum_d2": 0.0,
      "retail_diff": 0.0,
      "arb_diff": 0.0
    }
  },
  "seconds_per_simulation": 0.5977309576610569
}
