{"key":"d5-s23-cancel-far-only","idea":"After an exactly one-tick rival retreat, cancel only deeper own orders and preserve the best own price queue position on spreads 2 and 3.","approach":"Verified RC SHA-256. Appended a wrapper using the same retreat trigger as RC. On the retreated side it retains all own orders at the best own price, restores their tracking if the base strategy canceled them, and cancels deeper orders. Screened suppression of placements versus allowing funded placements; selected by paired tuning mean on spreads 2 and 3.","tried":[{"name":"far_suppress","code_sha256":"f135c96276a0bc55e504081a3928c4c03cf525b8b4888acae408e5d0a2c46957","tuning_mean_diff":0.04076674356226448,"se":0.03871456651494439},{"name":"far_place","code_sha256":"2563818fb550ab21b8da220c417e4f40d00506560b0ee2e4c637562353f61705","tuning_mean_diff":-0.8635311075292443,"se":0.35675246001624283}],"next":"Holdout gain does not clear two standard errors; do not advance this wrapper.","code":"\"\"\"Exact per-spread merge: c1-pairs, c2-queue, a3-ledger, c4-all; no fixes.\"\"\"\nimport math\nfrom orderbook_pm_challenge.strategy import BaseStrategy\nfrom orderbook_pm_challenge.types import CancelOrder, PlaceOrder, Side\n\ndef _spread1():\n    P = dict(lam_r=0.25, m=5.0, sig_n=1.2, lam_j=0.0019, sig_j=0.35, sig=0.02, qmax=3000.0, rmin=2, kA=0.7, kL=0.15, pL=0.05, ammo=1.0, ydem=0.4, W=200.0, fy=0.6, ammo_q=60.0, ammo_pmax=0.05, ammo_maxpay=0.02, fb=0.9, fu=0.7, xu=0.1, sticky=1.0, min_ahead=2.0, keep_hi=1.5, keep_lo=0.7, Hu=300.0, bins=8.0, filt=1.0, uni=0.01, jumpinfo=1.0, dmin=0.0, kLb=0.08, kLf=0.08, pinf=1.0, pre=0.0, H1=100.0, ydf=0.6, Wf=2000.0, g_hi=0.15, g_lo=0.15, qf=400.0, pmaxf=0.05, pre_gap=1.0, ydf1=0.6, g1=5.0, f1=0.6, a1=100.0, nb1=0.0, gs=1.0, p1t=1.0, m1=1.0, zd=1.0, pfl=0.0005)\n    SQ2 = math.sqrt(2.0)\n    SQ2PI = math.sqrt(2.0 * math.pi)\n\n    def cdf(x):\n        return 0.5 * (1.0 + math.erf(x / SQ2))\n\n    def pdf(x):\n        return math.exp(-0.5 * x * x) / SQ2PI\n\n    def inv(p):\n        p = min(max(p, 1e-09), 1 - 1e-09)\n        t = math.sqrt(-2.0 * math.log(min(p, 1 - p)))\n        x = t - (2.515517 + 0.802853 * t + 0.010328 * t * t) / (1 + 1.432788 * t + 0.189269 * t * t + 0.001308 * t ** 3)\n        x = -x if p < 0.5 else x\n        for _ in range(2):\n            d = pdf(x)\n            if d < 1e-12:\n                break\n            x -= (cdf(x) - p) / d\n        return x\n\n    def lpm(k):\n        return pdf(k) + k * cdf(k)\n\n    def fl(q):\n        return math.floor(q * 100 + 1e-09) / 100\n    NODES = [(-2.2, 0.06), (-1.3, 0.17), (-0.6, 0.27), (0.6, 0.27), (1.3, 0.17), (2.2, 0.06)]\n    PROBE = 0.01\n    F_AH = 1\n    F_FL = 1\n    F_QB = 1\n    F_LK = 0\n    F_SB = 0\n    FLOW_CAPS = (0.03125, 0.0625, 0.125, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0)\n    FLOW_GRID = []\n    FLOW_PRIORS = []\n    for _rn, _rw in ((-math.sqrt(0.6), 5 / 18), (0.0, 4 / 9), (math.sqrt(0.6), 5 / 18)):\n        _r = 0.1265 + 0.0495 * _rn\n        for _mn, _mw in ((-0.906179845938664, 0.118463442528095), (-0.538469310105683, 0.239314335249683), (0.0, 0.284444444444444), (0.538469310105683, 0.239314335249683), (0.906179845938664, 0.118463442528095)):\n            _m = 4.488 + 1.848 * _mn\n            _parts = []\n            for _n in (1, 2, 3):\n                _v = math.log(1 + (math.exp(1.44) - 1) / _n)\n                _sg = math.sqrt(_v)\n                _mu = math.log(_n * _m) - _v / 2\n                _w = _r ** _n / math.factorial(_n)\n                _parts.append((_mu, _sg, _w))\n            _norm = []\n            for _c in FLOW_CAPS:\n                _prob = sum((w * (cdf((math.log(_c) - mu) / sg) - cdf((math.log(0.03) - mu) / sg)) for mu, sg, w in _parts))\n                _norm.append(math.log1p(_prob))\n            _tails = []\n            for _c in FLOW_CAPS:\n                _cdf = 1 + sum((w * cdf((math.log(_c) - mu) / sg) for mu, sg, w in _parts))\n                _tails.append(math.log(max(1e-100, 1 - math.exp(-_r) * _cdf)))\n            FLOW_GRID.append((_r, _m, _parts, _norm, _tails))\n            FLOW_PRIORS.append(math.log(_rw * _mw))\n    return (P, cdf, pdf, inv, lpm, fl, NODES, PROBE, F_AH, F_FL, F_QB, F_LK, F_SB, FLOW_CAPS, FLOW_GRID, FLOW_PRIORS)\n\ndef _spread2():\n    P = dict(lam_r=0.25, m=5.0, sig_n=1.2, lam_j=0.0019, sig_j=0.35, sig=0.02, qmax=3000.0, rmin=2, kA=0.7, kL=0.15, pL=0.05, ammo=1.0, ydem=0.4, W=200.0, fy=0.6, ammo_q=60.0, ammo_pmax=0.05, ammo_maxpay=0.02, fb=0.9, fu=0.7, xu=0.1, sticky=1.0, min_ahead=2.0, keep_hi=1.5, keep_lo=0.7, Hu=300.0, bins=8.0, filt=1.0, uni=0.01, jumpinfo=1.0, dmin=0.0, kLb=0.08, kLf=0.08, pinf=1.0, pre=0.0, H1=100.0, ydf=0.6, Wf=2000.0, g_hi=0.15, g_lo=0.15, qf=400.0, pmaxf=0.05, pre_gap=1.0, ydf1=0.6, g1=5.0, f1=0.6, a1=100.0, nb1=0.0, gs=1.0, p1t=1.0, m1=1.0, zd=1.0, pfl=0.0005)\n    SQ2 = math.sqrt(2.0)\n    SQ2PI = math.sqrt(2.0 * math.pi)\n\n    def cdf(x):\n        return 0.5 * (1.0 + math.erf(x / SQ2))\n\n    def pdf(x):\n        return math.exp(-0.5 * x * x) / SQ2PI\n\n    def inv(p):\n        p = min(max(p, 1e-09), 1 - 1e-09)\n        t = math.sqrt(-2.0 * math.log(min(p, 1 - p)))\n        x = t - (2.515517 + 0.802853 * t + 0.010328 * t * t) / (1 + 1.432788 * t + 0.189269 * t * t + 0.001308 * t ** 3)\n        x = -x if p < 0.5 else x\n        for _ in range(2):\n            d = pdf(x)\n            if d < 1e-12:\n                break\n            x -= (cdf(x) - p) / d\n        return x\n\n    def lpm(k):\n        return pdf(k) + k * cdf(k)\n\n    def fl(q):\n        return math.floor(q * 100 + 1e-09) / 100\n    NODES = [(-2.2, 0.06), (-1.3, 0.17), (-0.6, 0.27), (0.6, 0.27), (1.3, 0.17), (2.2, 0.06)]\n    PROBE = 0.01\n    return (P, cdf, pdf, inv, lpm, fl, NODES, PROBE)\n\ndef _spread3():\n    P = dict(lam_r=0.25, m=5.0, sig_n=1.2, lam_j=0.0019, sig_j=0.35, sig=0.02, qmax=3000.0, rmin=2, kA=0.7, kL=0.15, pL=0.05, ammo=1.0, ydem=0.4, W=200.0, fy=0.6, ammo_q=60.0, ammo_pmax=0.05, ammo_maxpay=0.02, fb=0.9, fu=0.7, xu=0.1, sticky=1.0, min_ahead=2.0, keep_hi=1.5, keep_lo=0.7, Hu=300.0, bins=8.0, filt=1.0, uni=0.01, jumpinfo=1.0, dmin=0.0, kLb=0.08, kLf=0.08, pinf=1.0, pre=0.0, H1=100.0, ydf=0.6, Wf=2000.0, g_hi=0.15, g_lo=0.15, qf=400.0, pmaxf=0.05, pre_gap=1.0, ydf1=0.6, g1=5.0, f1=0.6, a1=100.0, nb1=0.0, gs=1.0, p1t=1.0, m1=1.0, zd=1.0, pfl=0.0005)\n    SQ2 = math.sqrt(2.0)\n    SQ2PI = math.sqrt(2.0 * math.pi)\n\n    def cdf(x):\n        return 0.5 * (1.0 + math.erf(x / SQ2))\n\n    def pdf(x):\n        return math.exp(-0.5 * x * x) / SQ2PI\n\n    def inv(p):\n        p = min(max(p, 1e-09), 1 - 1e-09)\n        t = math.sqrt(-2.0 * math.log(min(p, 1 - p)))\n        x = t - (2.515517 + 0.802853 * t + 0.010328 * t * t) / (1 + 1.432788 * t + 0.189269 * t * t + 0.001308 * t ** 3)\n        x = -x if p < 0.5 else x\n        for _ in range(2):\n            d = pdf(x)\n            if d < 1e-12:\n                break\n            x -= (cdf(x) - p) / d\n        return x\n\n    def lpm(k):\n        return pdf(k) + k * cdf(k)\n\n    def fl(q):\n        return math.floor(q * 100 + 1e-09) / 100\n    NODES = [(-2.2, 0.06), (-1.3, 0.17), (-0.6, 0.27), (0.6, 0.27), (1.3, 0.17), (2.2, 0.06)]\n    PROBE = 0.01\n    return (P, cdf, pdf, inv, lpm, fl, NODES, PROBE)\n\ndef _spread4():\n    P = dict(lam_r=0.25, m=5.0, sig_n=1.2, lam_j=0.0019, sig_j=0.35, sig=0.02, qmax=3000.0, rmin=2, kA=0.7, kL=0.15, pL=0.05, ammo=1.0, ydem=0.4, W=200.0, fy=0.6, ammo_q=60.0, ammo_pmax=0.05, ammo_maxpay=0.02, fb=0.9, fu=0.7, xu=0.1, sticky=1.0, min_ahead=2.0, keep_hi=1.5, keep_lo=0.7, Hu=300.0, bins=8.0, filt=1.0, uni=0.01, jumpinfo=1.0, dmin=0.0, kLb=0.08, kLf=0.08, pinf=1.0, pre=0.0, H1=100.0, ydf=0.6, Wf=2000.0, g_hi=0.15, g_lo=0.15, qf=400.0, pmaxf=0.05, pre_gap=1.0, ydf1=0.6, g1=5.0, f1=0.6, a1=100.0, nb1=0.0, gs=1.0, p1t=1.0, m1=1.0, zd=1.0, pfl=0.0005)\n    SQ2 = math.sqrt(2.0)\n    SQ2PI = math.sqrt(2.0 * math.pi)\n\n    def cdf(x):\n        return 0.5 * (1.0 + math.erf(x / SQ2))\n\n    def pdf(x):\n        return math.exp(-0.5 * x * x) / SQ2PI\n\n    def inv(p):\n        p = min(max(p, 1e-09), 1 - 1e-09)\n        t = math.sqrt(-2.0 * math.log(min(p, 1 - p)))\n        x = t - (2.515517 + 0.802853 * t + 0.010328 * t * t) / (1 + 1.432788 * t + 0.189269 * t * t + 0.001308 * t ** 3)\n        x = -x if p < 0.5 else x\n        for _ in range(2):\n            d = pdf(x)\n            if d < 1e-12:\n                break\n            x -= (cdf(x) - p) / d\n        return x\n\n    def lpm(k):\n        return pdf(k) + k * cdf(k)\n\n    def fl(q):\n        return math.floor(q * 100 + 1e-09) / 100\n    NODES = [(-2.2, 0.06), (-1.3, 0.17), (-0.6, 0.27), (0.6, 0.27), (1.3, 0.17), (2.2, 0.06)]\n    PROBE = 0.01\n    return (P, cdf, pdf, inv, lpm, fl, NODES, PROBE)\n\nclass Strategy(BaseStrategy):\n\n    def __init__(self):\n        self.n = 0\n        self.ahead = set()\n        self.res = {}\n        self.bc = None\n        self.bw = None\n        self.st = 0.5\n        self.pcb = self.pca = None\n        self.pb = set()\n        self.pa = set()\n        self.tb = 0\n        self.s = None\n        self.flow_notional = 0.0\n        self.flow_exposure = 0\n        self.last_ask_tick = None\n        self.last_quote_exposed = False\n        self.last_flow_ca = None\n        self.last_flow_cap = 0.0\n        self.last_flow_correction = 1.0\n        self.params = None\n\n    def _oid(self, tag):\n        self.n += 1\n        return tag + str(self.n)\n\n    def on_step(self, state):\n        H = max(1, state.steps_remaining)\n        cb = state.competitor_best_bid_ticks or 0\n        ca = state.competitor_best_ask_ticks or 100\n        initializing = self.s is None\n        if initializing:\n            self.s = max(1, (ca - cb + 1) // 2)\n            if self.s == 1:\n                self._scope = _spread1()\n            elif self.s == 2:\n                self._scope = _spread2()\n            elif self.s == 3:\n                self._scope = _spread3()\n            elif self.s == 4:\n                self._scope = _spread4()\n            self.params = self._scope[0].copy()\n        if self.s == 1:\n            _unused, cdf, pdf, inv, lpm, fl, NODES, PROBE, F_AH, F_FL, F_QB, F_LK, F_SB, FLOW_CAPS, FLOW_GRID, FLOW_PRIORS = self._scope\n        elif self.s == 2:\n            _unused, cdf, pdf, inv, lpm, fl, NODES, PROBE = self._scope\n        elif self.s == 3:\n            _unused, cdf, pdf, inv, lpm, fl, NODES, PROBE = self._scope\n        elif self.s == 4:\n            _unused, cdf, pdf, inv, lpm, fl, NODES, PROBE = self._scope\n        if initializing:\n            if self.s == 1:\n                self.fl_obs = ()\n                self.fl_scores = FLOW_PRIORS.copy()\n                self.fl_bins = [0] * len(FLOW_CAPS)\n                self.fl_rate = 0.568734\n                self.fl_r = 0.1265\n                self.fl_m = 4.488\n                self.fl_buy_sum = self.fl_sell_sum = 0.0\n                self.fl_buy_exp = self.fl_sell_exp = 0.0\n                self.fl_exp = 0\n                self.fl_dirty = False\n                self.fl_ahead = set()\n                self.fl_safe_n = 0\n                self.fl_sbins = [0] * len(FLOW_CAPS)\n            elif self.s == 2:\n                self.params.update(dict(flow_prior=200, flow_level=0.6, flow_strength=1.0, flow_safety=2.0, flow_exposure_min=5.0))\n                self.params.update({'kLf': 0.16})\n            elif self.s == 4:\n                self.f4_exposure = [0, 0]\n                self.f4_events = [0, 0]\n                self.f4_weights = [[0.0] * 9, [0.0] * 9]\n                self.f4_means = [2.64 + i * (6.336 - 2.64) / 8 for i in range(9)]\n                self.f4_mu = [math.log(m) - 0.72 + 0.065 for m in self.f4_means]\n                self.f4_last = [None, None]\n                self.f4_rate = 0.1265\n                self.f4_mean = 4.488\n                self.f4_flow = self.f4_rate * self.f4_mean\n                self.f4_extreme = inv(1 - 1e-06)\n            if self.s == 1:\n                self.params.update({'dmin': 0.3, 'pfl': 1e-06})\n            if self.s == 3:\n                self.params.update({'flow_prior': 200, 'flow_level': 0.6, 'flow_strength': 1.0, 'flow_safety': 2.0, 'flow_exposure_min': 5.0})\n        P = self.params\n        if self.s == 1:\n            s1 = self.s == 1\n            AH = s1 and F_AH\n            FL = s1 and F_FL\n            QB = s1 and F_QB\n            LK = s1 and F_LK\n            SB = s1 and F_SB\n        elif self.s == 2:\n            if self.last_quote_exposed and ca <= self.last_flow_ca + 1:\n                self.flow_exposure += 1\n                self.flow_notional += min(self.last_flow_cap, state.sell_filled_quantity * self.last_ask_tick / 100.0) * self.last_flow_correction\n        elif self.s == 3:\n            if self.last_quote_exposed and ca <= self.last_flow_ca + 1:\n                self.flow_exposure += 1\n                self.flow_notional += min(self.last_flow_cap, state.sell_filled_quantity * self.last_ask_tick / 100.0) * self.last_flow_correction\n        elif self.s == 4:\n            for side, filled, bound in ((0, state.sell_filled_quantity, ca), (1, state.buy_filled_quantity, cb)):\n                last = self.f4_last[side]\n                if last is None:\n                    continue\n                tick, conv, cap, old_bound, ids = last\n                if side == 0 and bound > old_bound + 1 or (side == 1 and bound < old_bound - 1):\n                    continue\n                remaining = sum((o.remaining_quantity for o in state.own_orders if o.order_id in ids))\n                value = max(0.0, cap - remaining * conv)\n                self.f4_exposure[side] += 1\n                if value > 0.01:\n                    self.f4_events[side] += 1\n                    censored = remaining < 0.011\n                    logv = math.log(max(value, 0.01))\n                    weights = self.f4_weights[side]\n                    for i, mu4 in enumerate(self.f4_mu):\n                        z4 = (logv - mu4) / 1.2\n                        weights[i] += math.log(max(1e-12, 1.0 - cdf(z4))) if censored else -0.5 * z4 * z4\n            if state.step % 25 == 0:\n                exposure = sum(self.f4_exposure)\n                events = sum(self.f4_events)\n                event_probability = (events + 80.0 * (1.0 - math.exp(-0.1265))) / (exposure + 80.0)\n                self.f4_rate = max(0.077, min(0.176, -math.log(max(1e-06, 1.0 - event_probability))))\n                weights = [a + b for a, b in zip(*self.f4_weights)]\n                peak = max(weights)\n                weights = [math.exp(w - peak) for w in weights]\n                self.f4_mean = sum((m * w for m, w in zip(self.f4_means, weights))) / sum(weights)\n                self.f4_flow = self.f4_rate * self.f4_mean\n        lo, hi = (cb, ca)\n        for o in state.own_orders:\n            if o.side is Side.BUY:\n                lo = max(lo, o.price_ticks)\n            else:\n                hi = min(hi, o.price_ticks)\n        if P['pinf'] > 0:\n            sb = {o.price_ticks for o in state.own_orders if o.side is Side.BUY and o.remaining_quantity <= PROBE + 1e-09}\n            sa = {o.price_ticks for o in state.own_orders if o.side is Side.SELL and o.remaining_quantity <= PROBE + 1e-09}\n            ea = self.pa - sa\n            eb = self.pb - sb\n            if sa and ea:\n                lo = max(lo, min(max(ea), hi))\n            if eb and (sb or min(eb) <= P['p1t']):\n                hi = min(hi, max(min(eb), lo))\n        if P['jumpinfo'] > 0 and self.pcb is not None:\n            if ca > self.pca + 1:\n                lo = max(lo, ca - 1)\n            if cb < self.pcb - 1:\n                hi = min(hi, cb + 1)\n        self.pcb, self.pca = (cb, ca)\n        if lo > hi:\n            lo, hi = (hi, lo)\n        wid = max(hi - lo, 1e-06)\n        nb = max(2, min(48, int(round(wid * P['bins']))))\n        cs = [lo + (i + 0.5) * wid / nb for i in range(nb)]\n        if self.bc is None or P['filt'] <= 0:\n            ws = [1.0 / nb] * nb\n        else:\n            sg = max(self.st, 0.6 * wid / nb)\n            k = -0.5 / (sg * sg)\n            ws = []\n            uni = P['uni'] * sg\n            if self.s == 1:\n                prior = tuple(zip(self.bc, self.bw))\n                exp = math.exp\n                for c in cs:\n                    t = uni\n                    for ci, wi in prior:\n                        d = c - ci\n                        d2 = d * d * k\n                        if d2 > -12.5:\n                            t += wi * exp(d2)\n                    ws.append(t)\n            elif self.s == 2:\n                for c in cs:\n                    t = uni\n                    for ci, wi in zip(self.bc, self.bw):\n                        d = c - ci\n                        d2 = d * d * k\n                        if d2 > -12.5:\n                            t += wi * math.exp(d2)\n                    ws.append(t)\n            elif self.s == 3:\n                for c in cs:\n                    t = uni\n                    for ci, wi in zip(self.bc, self.bw):\n                        d = c - ci\n                        d2 = d * d * k\n                        if d2 > -12.5:\n                            t += wi * math.exp(d2)\n                    ws.append(t)\n            elif self.s == 4:\n                exp = math.exp\n                if self.bc == cs and 1.0 <= wid <= 6.0 and (nb == 8 * wid):\n                    kernel = []\n                    c0 = cs[0]\n                    for ci in self.bc:\n                        d = c0 - ci\n                        d2 = d * d * k\n                        kernel.append(exp(d2) if d2 > -12.5 else 0.0)\n                    kernel = kernel[:0:-1] + kernel\n                    for i in range(nb):\n                        t = uni\n                        start = nb - 1 - i\n                        for wi, e in zip(self.bw, kernel[start:start + nb]):\n                            if e:\n                                t += wi * e\n                        ws.append(t)\n                else:\n                    previous = tuple(zip(self.bc, self.bw))\n                    for c in cs:\n                        t = uni\n                        for ci, wi in previous:\n                            d = c - ci\n                            d2 = d * d * k\n                            if d2 > -12.5:\n                                t += wi * exp(d2)\n                        ws.append(t)\n            tot = sum(ws)\n            ws = [w / tot for w in ws]\n        self.bc, self.bw = (cs, ws)\n        mean_t = sum((c * w for c, w in zip(cs, ws)))\n        var_t = max(sum((c * c * w for c, w in zip(cs, ws))) - mean_t * mean_t, 0.0)\n        phat = min(max(mean_t / 100.0, 0.002), 0.998)\n        var = P['sig'] ** 2 + P['lam_j'] * P['sig_j'] ** 2\n        sd = math.sqrt(H * var)\n        self.tb = self.tb + 1 if hi <= 1 else 0\n        if self.tb > 0 and P['zd'] > 0:\n            phat = min(phat, max(P['pfl'], cdf(inv(0.01) - P['zd'] * 0.02 * math.sqrt(self.tb) / sd)))\n        z = inv(phat)\n        Z = z * sd\n        sp = pdf(z) / sd * P['sig']\n        self.st = sp * 100.0\n        if self.s == 1:\n            if FL:\n                remaining = {o.order_id: o.remaining_quantity for o in state.own_orders} if self.fl_obs else {}\n                for px, ci, buying, previous, tick in self.fl_obs:\n                    qty = max(0.0, sum((q - remaining.get(oid, 0.0) for oid, q in previous)))\n                    x = qty * px\n                    cap = FLOW_CAPS[ci]\n                    gap = tick / 100.0 - phat if buying else phat - tick / 100.0\n                    safe = gap > max(0.005, 2.0 * math.sqrt(var_t) / 100.0)\n                    if 0 < x < 0.03:\n                        continue\n                    if x >= cap:\n                        if safe:\n                            self.fl_sbins[ci] += 1\n                            self.fl_exp += 1\n                            self.fl_dirty = True\n                        continue\n                    if safe:\n                        self.fl_safe_n += 1\n                    else:\n                        self.fl_bins[ci] += 1\n                    self.fl_exp += 1\n                    self.fl_dirty = True\n                    if buying:\n                        self.fl_buy_exp += 1\n                    else:\n                        self.fl_sell_exp += 1\n                    if x > 0:\n                        lx = math.log(x)\n                        for i, (r, m, parts, norm, tails) in enumerate(FLOW_GRID):\n                            density = sum((w * pdf((lx - mu) / sg) / sg for mu, sg, w in parts))\n                            self.fl_scores[i] += math.log(max(density, 1e-100))\n                if state.step % 100 == 0 and (self.fl_dirty or state.step == 0):\n                    bins = [(i, n) for i, n in enumerate(self.fl_bins) if n]\n                    sbins = [(i, n) for i, n in enumerate(self.fl_sbins) if n]\n                    logs = [score - sum((n * g[3][i] for i, n in bins)) - g[0] * self.fl_safe_n + sum((n * g[4][i] for i, n in sbins)) for score, g in zip(self.fl_scores, FLOW_GRID)]\n                    mx = max(logs)\n                    weights = [math.exp(v - mx) for v in logs]\n                    den = sum(weights)\n                    self.fl_dirty = False\n                    self.fl_rate = sum((w * g[0] * g[1] for w, g in zip(weights, FLOW_GRID))) / den\n                    self.fl_r = sum((w * g[0] for w, g in zip(weights, FLOW_GRID))) / den\n                    self.fl_m = sum((w * g[1] for w, g in zip(weights, FLOW_GRID))) / den\n            s = math.sqrt(sp * sp + var_t / 10000.0 + 1e-08)\n        s = math.sqrt(sp * sp + var_t / 10000.0 + 1e-08)\n        sd1 = math.sqrt(max(1.0, H - 1.0) * var)\n        jp = [(cdf((Z + n * P['sig_j']) / sd1), w) for n, w in NODES]\n        lj = P['lam_j']\n\n        def AB(x):\n            k = (x - phat) / s\n            a = s * lpm(k)\n            b = a - (x - phat)\n            if self.s == 1:\n                ja = sum((w * max(0.0, x - p) for p, w in jp))\n                jb = sum((w * max(0.0, p - x) for p, w in jp))\n            elif self.s == 2:\n                ja = sum((w * max(0.0, x - p) for p, w in jp))\n                jb = sum((w * max(0.0, p - x) for p, w in jp))\n            elif self.s == 3:\n                ja = sum((w * max(0.0, x - p) for p, w in jp))\n                jb = sum((w * max(0.0, p - x) for p, w in jp))\n            elif self.s == 4:\n                ja = jb = 0.0\n                for p, w in jp:\n                    if x > p:\n                        ja += w * (x - p)\n                    else:\n                        jb += w * (p - x)\n            return ((1 - lj) * a + lj * ja, (1 - lj) * b + lj * jb)\n        if H == 1:\n\n            def AB(x):\n                return ((1 - phat) * x, phat * (1 - x))\n        rho = P['lam_r'] * 0.5\n        mu = math.log(P['m']) - 0.5 * P['sig_n'] ** 2\n        kA = P['kL'] if phat < P['pL'] else P['kA']\n        if self.s == 1:\n\n            def qsize(loss, gain, px, flow=False, cap=None):\n                loss *= kA\n                if gain <= 0:\n                    return 0.0\n                rr = 0.125 + 0.5 * (self.fl_r - 0.125) if flow and FL else rho\n                mm = math.log(5.0 + 0.5 * (self.fl_m - 5.0)) - 0.5 * P['sig_n'] ** 2 if flow and FL else mu\n                tail = loss / (rr * gain)\n                if tail >= 1.0:\n                    return 0.0\n                return min(cap if cap is not None else P['qmax'], math.exp(mm + P['sig_n'] * inv(1 - max(tail, 1e-06))) / px)\n        elif self.s == 2:\n\n            def qsize(loss, gain, px):\n                loss *= kA\n                if gain <= 0:\n                    return 0.0\n                tail = loss / (rho * gain)\n                if tail >= 1.0:\n                    return 0.0\n                return min(P['qmax'], math.exp(mu + P['sig_n'] * inv(1 - max(tail, 1e-06))) / px)\n        elif self.s == 3:\n\n            def qsize(loss, gain, px):\n                loss *= kA\n                if gain <= 0:\n                    return 0.0\n                tail = loss / (rho * gain)\n                if tail >= 1.0:\n                    return 0.0\n                return min(P['qmax'], math.exp(mu + P['sig_n'] * inv(1 - max(tail, 1e-06))) / px)\n        elif self.s == 4:\n\n            def qsize(loss, gain, px):\n                loss *= kA\n                if gain <= 0:\n                    return 0.0\n                tail = loss / (rho * gain)\n                if tail >= 1.0:\n                    return 0.0\n                if tail <= 1e-06:\n                    return min(P['qmax'], math.exp(mu + P['sig_n'] * self.f4_extreme) / px)\n                return min(P['qmax'], math.exp(mu + P['sig_n'] * inv(1 - max(tail, 1e-06))) / px)\n        ptk = phat * 100\n\n        def qbid(t):\n            if not 1 <= t <= 99:\n                return 0.0\n            if self.s == 4:\n                if phat * 100 - t < P['dmin']:\n                    return 0.0\n            a, b = AB(t / 100.0)\n            if phat * 100 - t < P['dmin']:\n                return 0.0\n            if P['nb1'] > 0 and self.s == 1 and (t == 1) and (ptk < 1.0):\n                return 0.0\n            if phat < P['pL']:\n                ytg = P['ydem'] * min(H, P['W']) / max(ca - 1, ptk + 1) * 100.0\n                a *= (P['kLb'] if state.yes_inventory < ytg else P['kLf']) / P['kL']\n            return qsize(a, b, max(phat, 0.05))\n\n        def qask(t):\n            if not 1 <= t <= 99:\n                return 0.0\n            if self.s == 4:\n                if t - phat * 100 < P['dmin']:\n                    return 0.0\n            a, b = AB(t / 100.0)\n            if t - phat * 100 < P['dmin']:\n                return 0.0\n            if self.s == 1:\n                return qsize(b, a, t / 100.0, flow=True, cap=15000 if AH and t == 2 and (phat < 0.01) else None)\n            elif self.s == 2:\n                return qsize(b, a, t / 100.0)\n            elif self.s == 3:\n                return qsize(b, a, t / 100.0)\n            elif self.s == 4:\n                if P['pL'] <= phat <= 0.95:\n                    b *= 1.4\n                tail = b * kA / max(self.f4_rate * a, 1e-30)\n                if a <= 0 or tail >= 1.0:\n                    return 0.0\n                return min(P['qmax'], math.exp(math.log(self.f4_mean) - 0.72 + 1.2 * (self.f4_extreme if tail <= 1e-06 else inv(1 - tail))) / (t / 100.0))\n                return qsize(b, a, t / 100.0)\n        bids = [o for o in state.own_orders if o.side is Side.BUY and o.remaining_quantity > PROBE + 1e-09]\n        asks = [o for o in state.own_orders if o.side is Side.SELL and o.remaining_quantity > PROBE + 1e-09]\n        sticky = P['sticky'] > 0\n        if self.s == 4:\n            ma_ask = 50.0 if self.s == 4 and phat < 0.05 else P['min_ahead']\n\n        def top(orders, comp, step):\n            if self.s == 1:\n                if sticky and sum((o.remaining_quantity for o in orders if o.price_ticks == comp and o.order_id in self.ahead)) >= (PROBE + 0.01 if QB and step == 1 else P['min_ahead']):\n                    return comp\n            elif self.s == 2:\n                if sticky and sum((o.remaining_quantity for o in orders if o.price_ticks == comp and o.order_id in self.ahead)) >= (P['min_ahead'] if self.s != 2 else max(P['min_ahead'], 400.0 / max(comp, 1))):\n                    return comp\n            elif self.s == 3:\n                threshold = max(P['min_ahead'], 20 * 100.0 / comp) if self.s == 3 and step == -1 and (1 <= comp <= 5) else P['min_ahead']\n                if sticky and sum((o.remaining_quantity for o in orders if o.price_ticks == comp and o.order_id in self.ahead)) >= threshold:\n                    return comp\n            elif self.s == 4:\n                if sticky and sum((o.remaining_quantity for o in orders if o.price_ticks == comp and o.order_id in self.ahead)) >= (ma_ask if step < 0 else P['min_ahead']):\n                    return comp\n            return comp + step\n        bid_t = top(bids, cb, 1)\n        ask_t = top(asks, ca, -1)\n        qb = qbid(bid_t)\n        if self.s == 2:\n            s2f = self.s == 2 and bid_t == cb and (qb > 0) and (cb / 100.0 < phat)\n        elif self.s == 4:\n            if phat < 0.05 and bid_t >= 2:\n                qb *= 0.5\n        qa = qask(ask_t)\n        if self.s == 1:\n            if ask_t == 2 and ask_t < ca and (phat < 0.01):\n                qa *= 5\n        Y = state.yes_inventory\n        if ask_t == 1 and H > P['H1'] and (P['pre'] > 0):\n            qa = qa if Y >= P['a1'] > 0 else 0.0\n        ptick = phat * 100\n        if self.s == 1:\n            flow_scale = max(0.4, min(1.9, 1.0 + 0.5 * (self.fl_rate / 0.568734 - 1))) if FL else 1.0\n        amt = 0\n        qam = 0.0\n        if P['ammo'] > 0 and ask_t >= 2 and (phat < max(P['ammo_pmax'], P['pmaxf'])):\n            wealth = state.cash + Y * phat\n            x = max(ask_t, ptick + 1) / 100.0\n            capw = P['fy'] * wealth / max(phat, 0.005)\n            if self.s == 1:\n                target = min(flow_scale * P['ydem'] * min(H, P['W']) / x, capw)\n                full = min(flow_scale * P['ydf'] * min(H, P['Wf']) / x, capw) if phat < P['pmaxf'] else 0.0\n            elif self.s == 2:\n                target = min(P['ydem'] * min(H, P['W']) / x, capw)\n                full = min(P['ydf'] * min(H, P['Wf']) / x, capw) if phat < P['pmaxf'] else 0.0\n            elif self.s == 3:\n                flow_scale = self.f4_flow / 0.6 if self.s == 4 else 1.0\n                target = min(flow_scale * P['ydem'] * min(H, P['W']) / x, capw)\n                target = min(target, qa)\n                full = min(flow_scale * P['ydf'] * min(H, P['Wf']) / x, capw) if phat < P['pmaxf'] else 0.0\n            elif self.s == 4:\n                flow_scale = self.f4_flow / 0.6 if self.s == 4 else 1.0\n                target = min(flow_scale * P['ydem'] * min(H, P['W']) / x, capw)\n                full = min(flow_scale * P['ydf'] * min(H, P['Wf']) / x, capw) if phat < P['pmaxf'] else 0.0\n            t = max(1, min(99, int(math.ceil(ptick + 1e-09))))\n            g = t - ptick\n            if Y < full and g <= P['g_hi'] and (bid_t <= t < ask_t):\n                amt, qam = (t, min(P['qf'], full - Y))\n            elif Y < target and phat < P['ammo_pmax'] and (bid_t <= t < ask_t) and (t / 100.0 - phat < P['ammo_maxpay']):\n                amt, qam = (t, min(P['ammo_q'], target - Y))\n            elif Y < full and t >= 2 and (1.0 - g <= P['g_lo']):\n                amt, qam = (t - 1, min(P['qf'], full - Y))\n        if P['pre'] > 0 and ca == 2 and (phat < 0.01) and (H > P['H1']) and (Y < P['pre']) and (not qam) and (1.0 - ptick < P['pre_gap']):\n            amt, qam = (1, min(P['ammo_q'], P['pre'] - Y))\n        q1 = 0.0\n        if P['ydf1'] > 0 and P['m1'] < ptick < P['g1'] + 1.0 and (amt != 1):\n            if self.s == 1:\n                stock_rate = flow_scale * P['ydf1']\n            elif self.s == 2:\n                stock_rate = P['ydf1']\n                flow = (self.flow_notional + P['flow_prior'] * P['flow_level']) / (P['flow_prior'] + self.flow_exposure)\n                scale = max(0.5, min(2.0, flow / P['flow_level']))\n                stock_rate *= 1.0 + P['flow_strength'] * (scale - 1.0)\n            elif self.s == 3:\n                stock_rate = P['ydf1']\n                flow = (self.flow_notional + P['flow_prior'] * P['flow_level']) / (P['flow_prior'] + self.flow_exposure)\n                scale = max(0.5, min(2.0, flow / P['flow_level']))\n                stock_rate *= 1.0 + P['flow_strength'] * (scale - 1.0)\n            elif self.s == 4:\n                stock_rate = P['ydf1']\n                stock_rate *= self.f4_flow / 0.6\n            q1 = max(0.0, stock_rate * min(H, P['Wf']) / (self.s / 100.0) - Y)\n        if 0.02 < phat < 0.1:\n            ct = max(2, min(99, int(math.floor(ptick))))\n            wealth = state.cash + Y * phat\n            if self.s == 1:\n                goal = min(flow_scale * qa, 0.3 * max(wealth, 0.0) / phat)\n            elif self.s == 2:\n                goal = min(1 * qa, 0.3 * max(wealth, 0.0) / phat)\n            elif self.s == 3:\n                goal = min(1 * qa, 0.3 * max(wealth, 0.0) / phat)\n            elif self.s == 4:\n                goal = min(1 * qa, 0.3 * max(wealth, 0.0) / phat)\n            if Y < goal and ct < ask_t:\n                amt, qam = (ct, min(3000.0, goal - Y))\n        if self.s == 1:\n            if SB and 2 <= amt <= 5:\n                amt, qam = (0, 0.0)\n        actions = []\n        free = state.free_cash - 2.0\n        keep_ask = 0.0\n        new_b = []\n        new_a = []\n\n        def cancel(o):\n            nonlocal free\n            actions.append(CancelOrder(o.order_id))\n            x = o.price_ticks / 100.0\n            if o.side is Side.BUY:\n                free += x * o.remaining_quantity\n            else:\n                free += (1 - x) * min(self.res.get(o.order_id, 0.0), o.remaining_quantity)\n            self.ahead.discard(o.order_id)\n            self.res.pop(o.order_id, None)\n        for o in state.own_orders:\n            if o.remaining_quantity <= PROBE + 1e-09:\n                cancel(o)\n        kept_ids = set()\n\n        def manage(orders, t, q, comp):\n            kept = 0.0\n            if self.s == 1:\n                banked = {}\n                bound_t, bound_q = (t, q)\n            elif self.s == 2:\n                buy = comp == cb\n                held = {}\n                for o in orders:\n                    x = o.price_ticks\n                    gain = ptk - x if buy else x - ptk\n                    if x == t and q > 0 and (kept + o.remaining_quantity <= max(q * P['keep_hi'], 1.0) or (x == comp and o.order_id in self.ahead and (ptk <= 10.0) and (gain >= 0.0))):\n                        kept += o.remaining_quantity\n                        kept_ids.add(o.order_id)\n                        continue\n                    if x == comp and x != t and (o.order_id in self.ahead) and (gain >= 1.0):\n                        if x not in held:\n                            held[x] = [0.0, qbid(x) if buy else qask(x)]\n                        h = held[x]\n                        if h[0] + o.remaining_quantity <= max(h[1], 1.0) and h[1] > 0:\n                            h[0] += o.remaining_quantity\n                            kept_ids.add(o.order_id)\n                            continue\n                    cancel(o)\n                return kept\n            for o in orders:\n                if self.s == 1:\n                    ah = o.order_id in self.ahead\n                    if AH and ah and (o.remaining_quantity >= P['min_ahead']) and (o.price_ticks != t):\n                        if o.side is Side.SELL and o.price_ticks > t or (o.side is Side.BUY and o.price_ticks < t):\n                            enough = bound_q > 0 and (o.remaining_quantity <= bound_q if o.side is Side.BUY else o.remaining_quantity * o.price_ticks <= min(bound_q, P['qmax']) * bound_t)\n                            if enough:\n                                kept_ids.add(o.order_id)\n                                continue\n                            if o.price_ticks == bound_t:\n                                capacity = bound_q\n                            else:\n                                capacity = qask(o.price_ticks) if o.side is Side.SELL else qbid(o.price_ticks)\n                                bound_t, bound_q = (o.price_ticks, capacity)\n                            if capacity > 0 and o.remaining_quantity <= max(capacity, 1.0):\n                                kept_ids.add(o.order_id)\n                                continue\n                    if QB and ah and (o.side is Side.BUY) and (o.price_ticks < t) and (banked.get(o.price_ticks, 0.0) + o.remaining_quantity <= P['keep_hi'] * qbid(o.price_ticks)):\n                        banked[o.price_ticks] = banked.get(o.price_ticks, 0.0) + o.remaining_quantity\n                        kept_ids.add(o.order_id)\n                        continue\n                    khi = 10.0 if AH and ah else P['keep_hi']\n                    if o.price_ticks == t and q > 0 and (kept + o.remaining_quantity <= max(q * khi, 1.0) or (s1 and ah and (o.side is Side.SELL) and (o.price_ticks <= 2)) or (LK and ah) or (QB and ah and (o.side is Side.BUY) and (o.price_ticks == comp))):\n                        kept += o.remaining_quantity\n                        kept_ids.add(o.order_id)\n                    else:\n                        cancel(o)\n                elif self.s == 2:\n                    if o.price_ticks == t and q > 0 and (kept + o.remaining_quantity <= max(q * P['keep_hi'], 1.0)):\n                        kept += o.remaining_quantity\n                        kept_ids.add(o.order_id)\n                    else:\n                        cancel(o)\n                elif self.s == 3:\n                    if o.price_ticks == t and q > 0 and (kept + o.remaining_quantity <= max(q * P['keep_hi'], 1.0)):\n                        kept += o.remaining_quantity\n                        kept_ids.add(o.order_id)\n                    else:\n                        cancel(o)\n                elif self.s == 4:\n                    if o.price_ticks == t and q > 0 and (kept + o.remaining_quantity <= max(q * (3.0 if self.s == 4 and o.side is Side.SELL and (o.order_id in self.ahead) and (o.price_ticks == comp) else P['keep_hi']), 1.0)):\n                        kept += o.remaining_quantity\n                        kept_ids.add(o.order_id)\n                    else:\n                        cancel(o)\n            return kept\n        if self.s == 1:\n            kb = manage(bids, bid_t, qb, cb)\n        elif self.s == 2:\n            if s2f and 1:\n                kb = 0.0\n                for o in bids:\n                    if o.price_ticks == bid_t and o.order_id in self.ahead:\n                        kb += o.remaining_quantity\n                        kept_ids.add(o.order_id)\n                    else:\n                        cancel(o)\n            elif 1 and bid_t == cb + 1:\n                qf = qbid(cb) if 1 else 1.0\n                fr = [o for o in bids if o.price_ticks == cb and o.order_id in self.ahead and (cb / 100.0 < phat - 0.0) and (qf > 0)]\n                for o in fr:\n                    kept_ids.add(o.order_id)\n                kb = manage([o for o in bids if o not in fr], bid_t, qb, cb)\n            else:\n                kb = manage(bids, bid_t, qb, cb)\n        elif self.s == 3:\n            kb = manage(bids, bid_t, qb, cb)\n        elif self.s == 4:\n            kb = manage(bids, bid_t, qb, cb)\n        ka = manage(asks, ask_t, qa, ca)\n        add_b = qb - kb if kb < qb * P['keep_lo'] and bid_t != cb else 0.0\n        add_a = qa - ka if ka < qa * P['keep_lo'] and ask_t != ca else 0.0\n        budget = P['fb'] * max(free, 0.0)\n        cost = add_b * bid_t / 100.0 + qam * amt / 100.0\n        if cost > budget:\n            f = budget / cost\n            add_b *= f\n            qam *= f\n            cost = budget\n        out = []\n        q1 = min(q1, P['f1'] * max(budget - cost, 0.0) * 100.0)\n        if q1 >= 0.01:\n            out.append(PlaceOrder(side=Side.BUY, price_ticks=1, quantity=fl(q1)))\n            free -= fl(q1) / 100.0 + 1e-06\n        if amt and qam >= 0.01:\n            q = fl(qam)\n            if self.s == 1:\n                if QB:\n                    oid = self._oid('m')\n                    out.append(PlaceOrder(side=Side.BUY, price_ticks=amt, quantity=q, client_order_id=oid))\n                    if amt > cb:\n                        self.ahead.add(oid)\n                else:\n                    out.append(PlaceOrder(side=Side.BUY, price_ticks=amt, quantity=q))\n            elif self.s == 2:\n                out.append(PlaceOrder(side=Side.BUY, price_ticks=amt, quantity=q))\n            elif self.s == 3:\n                out.append(PlaceOrder(side=Side.BUY, price_ticks=amt, quantity=q))\n            elif self.s == 4:\n                out.append(PlaceOrder(side=Side.BUY, price_ticks=amt, quantity=q))\n            free -= q * amt / 100.0 + 1e-06\n        if bid_t >= 1 and add_b >= 0.01:\n            q = fl(add_b)\n            if self.s == 4:\n                total_q = q\n                if ca <= 99 and bid_t > cb and (bid_t == ca - 4) and (q >= 4.0) and (q * bid_t / 100 >= 4 * P['m']):\n                    head = fl(q / 2)\n                    oid = self._oid('b')\n                    out.append(PlaceOrder(side=Side.BUY, price_ticks=bid_t, quantity=head, client_order_id=oid))\n                    self.ahead.add(oid)\n                    q = fl(q - head)\n            oid = self._oid('b')\n            out.append(PlaceOrder(side=Side.BUY, price_ticks=bid_t, quantity=q, client_order_id=oid))\n            if self.s == 1:\n                free -= q * bid_t / 100.0 + 1e-06\n            elif self.s == 2:\n                free -= q * bid_t / 100.0 + 1e-06\n            elif self.s == 3:\n                free -= q * bid_t / 100.0 + 1e-06\n            elif self.s == 4:\n                free -= total_q * bid_t / 100.0 + 1e-06\n            if bid_t > cb:\n                self.ahead.add(oid)\n        if ask_t <= 99 and add_a >= 0.01:\n            x = ask_t / 100.0\n            covk = sum((o.remaining_quantity - min(self.res.get(o.order_id, 0.0), o.remaining_quantity) for o in asks if o.order_id in kept_ids))\n            cov = max(0.0, Y - covk - 0.1)\n            unc = max(0.0, add_a - cov)\n            if unc > 0:\n                ub = max(0.0, free - (1 - P['fu']) * max(state.cash, 0.0)) if x >= P['xu'] else 0.0\n                if H < P['Hu'] and phat < 0.05:\n                    ub = max(0.0, free * (1 - H / P['Hu']))\n                unc = min(unc, ub / (1 - x))\n            q = fl(min(add_a, cov + unc))\n            if q >= 0.01:\n                oid = self._oid('a')\n                out.append(PlaceOrder(side=Side.SELL, price_ticks=ask_t, quantity=q, client_order_id=oid))\n                r = max(0.0, q - cov)\n                self.res[oid] = r\n                free -= r * (1 - x) + 1e-06\n                if ask_t < ca:\n                    self.ahead.add(oid)\n        f = int(math.floor(ptick + 1e-09))\n        r = max(int(P['rmin']), int(math.ceil(2.0 * s * 100)))\n        self.pb = set()\n        self.pa = set()\n        if free > 1.0:\n            for t in range(f, f + r + 1):\n                if cb < t < ca and 1 <= t <= 99:\n                    out.append(PlaceOrder(side=Side.BUY, price_ticks=t, quantity=PROBE))\n                    self.pb.add(t)\n            for t in range(f + 1 - r, f + 2):\n                if cb < t < ca and 1 <= t <= 99:\n                    out.append(PlaceOrder(side=Side.SELL, price_ticks=t, quantity=PROBE))\n                    self.pa.add(t)\n        if self.s == 1:\n            if FL:\n                if not kept_ids and (not any((o.quantity > PROBE for o in out))):\n                    self.fl_obs = ()\n                    self.fl_ahead.clear()\n                    return actions + out\n                for i, o in enumerate(out):\n                    if o.client_order_id is None and o.quantity > PROBE:\n                        out[i] = PlaceOrder(side=o.side, price_ticks=o.price_ticks, quantity=o.quantity, client_order_id=self._oid('f'))\n                live = []\n                oldids = {o.order_id for o in state.own_orders if o.order_id in kept_ids}\n                self.fl_ahead.intersection_update(oldids)\n                for o in state.own_orders:\n                    if o.order_id in kept_ids and o.remaining_quantity > PROBE:\n                        live.append((o.side, o.price_ticks, o.remaining_quantity, o.order_id))\n                for o in out:\n                    if o.quantity > PROBE:\n                        live.append((o.side, o.price_ticks, o.quantity, o.client_order_id))\n                        if o.side is Side.SELL and o.price_ticks < ca or (o.side is Side.BUY and o.price_ticks > cb):\n                            self.fl_ahead.add(o.client_order_id)\n                obs = []\n                for buying, side, comp in ((True, Side.SELL, ca), (False, Side.BUY, cb)):\n                    orders = [o for o in live if o[0] is side]\n                    if not orders:\n                        continue\n                    tick = min((o[1] for o in orders)) if buying else max((o[1] for o in orders))\n                    orders = [o for o in orders if o[1] == tick]\n                    if not all((o[3] in self.fl_ahead for o in orders)):\n                        continue\n                    if buying and tick > comp or (not buying and tick < comp):\n                        continue\n                    px = tick / 100.0 if buying else max(phat, 0.05)\n                    cap = sum((o[2] for o in orders)) * px\n                    if cap < 0.04:\n                        continue\n                    ci = 0\n                    while ci + 1 < len(FLOW_CAPS) and FLOW_CAPS[ci + 1] < cap - 0.01:\n                        ci += 1\n                    obs.append((px, ci, buying, [(o[3], o[2]) for o in orders], tick))\n                self.fl_obs = obs\n        elif self.s == 2:\n            self.last_ask_tick = ask_t\n            self.last_flow_ca = ca\n            exposed_qty = ka + sum((o.quantity for o in out if o.side is Side.SELL and o.price_ticks == ask_t and (o.quantity > PROBE)))\n            self.last_flow_cap = exposed_qty * ask_t / 100.0\n            self.last_quote_exposed = ask_t / 100.0 > phat + max(0.005, P['flow_safety'] * self.st / 100.0) and self.last_flow_cap >= P['flow_exposure_min']\n            if self.last_quote_exposed:\n                logcap = math.log(self.last_flow_cap)\n                mu_flow = math.log(P['m']) - 0.5 * P['sig_n'] ** 2\n                clipped = P['m'] * cdf((logcap - mu_flow - P['sig_n'] ** 2) / P['sig_n']) + self.last_flow_cap * (1.0 - cdf((logcap - mu_flow) / P['sig_n']))\n                self.last_flow_correction = min(3.0, P['m'] / max(clipped, 0.01))\n        elif self.s == 3:\n            self.last_ask_tick = ask_t\n            self.last_flow_ca = ca\n            exposed_qty = ka + sum((o.quantity for o in out if o.side is Side.SELL and o.price_ticks == ask_t and (o.quantity > PROBE)))\n            self.last_flow_cap = exposed_qty * ask_t / 100.0\n            self.last_quote_exposed = ask_t / 100.0 > phat + max(0.005, P['flow_safety'] * self.st / 100.0) and self.last_flow_cap >= P['flow_exposure_min']\n            if self.last_quote_exposed:\n                logcap = math.log(self.last_flow_cap)\n                mu_flow = math.log(P['m']) - 0.5 * P['sig_n'] ** 2\n                clipped = P['m'] * cdf((logcap - mu_flow - P['sig_n'] ** 2) / P['sig_n']) + self.last_flow_cap * (1.0 - cdf((logcap - mu_flow) / P['sig_n']))\n                self.last_flow_correction = min(3.0, P['m'] / max(clipped, 0.01))\n        elif self.s == 4:\n            self.f4_last = [None, None]\n            for side, tick, bound, conv, distance in ((0, ask_t, ca, ask_t / 100.0, ask_t / 100.0 - phat), (1, bid_t, cb, max(phat, 0.05), phat - bid_t / 100.0)):\n                if distance < max(0.01, 3.0 * self.st / 100.0):\n                    continue\n                if side == 0:\n                    if not (ask_t < ca or any((o.price_ticks == ask_t and o.order_id in self.ahead for o in asks))):\n                        continue\n                    orders = asks\n                    order_side = Side.SELL\n                else:\n                    if not (bid_t > cb or any((o.price_ticks == bid_t and o.order_id in self.ahead for o in bids))):\n                        continue\n                    if qam > 0 and amt >= bid_t or (q1 > 0 and bid_t <= 1):\n                        continue\n                    orders = bids\n                    order_side = Side.BUY\n                tracked = {o.order_id: o.remaining_quantity for o in orders if o.order_id in kept_ids and o.price_ticks == tick}\n                tracked.update({o.client_order_id: o.quantity for o in out if o.side is order_side and o.price_ticks == tick and (o.client_order_id is not None)})\n                cap = sum(tracked.values()) * conv\n                if cap >= 0.5:\n                    self.f4_last[side] = (tick, conv, cap, bound, tracked)\n        return actions + out\n\n\n_IncumbentStrategy = Strategy\n\nclass Strategy(_IncumbentStrategy):\n    \"\"\"Cancel a rival-retreated side for 1 callbacks, spreads 2/3 only.\"\"\"\n    def __init__(self):\n        super().__init__()\n        self._retreat_previous = (None, None)\n        self._retreat_left = {Side.BUY: 0, Side.SELL: 0}\n\n    def on_step(self, state):\n        bid = state.competitor_best_bid_ticks\n        ask = state.competitor_best_ask_ticks\n        old_bid, old_ask = self._retreat_previous\n        self._retreat_previous = (bid, ask)\n        actions = super().on_step(state)\n        if self.s not in (2, 3):\n            return actions\n        for side, retreat in (\n            (Side.BUY, bid is not None and old_bid is not None and bid == old_bid - 1),\n            (Side.SELL, ask is not None and old_ask is not None and ask == old_ask + 1),\n        ):\n            if retreat:\n                self._retreat_left[side] = 1\n        blocked = {side for side, left in self._retreat_left.items() if left > 0}\n        for side in blocked:\n            self._retreat_left[side] -= 1\n        if not blocked:\n            return actions\n        # Suppress every placement, including probes, on a blocked side.\n        out = []\n        for action in actions:\n            if isinstance(action, PlaceOrder) and action.side in blocked:\n                self.ahead.discard(action.client_order_id)\n                self.res.pop(action.client_order_id, None)\n            else:\n                out.append(action)\n        canceled = {a.order_id for a in out if isinstance(a, CancelOrder)}\n        out.extend(CancelOrder(o.order_id) for o in state.own_orders\n                   if o.side in blocked and o.order_id not in canceled)\n        # Do not interpret suppressed probes as fills on the next callback.\n        if Side.BUY in blocked:\n            self.pb.clear()\n        if Side.SELL in blocked:\n            self.pa.clear()\n            self.last_quote_exposed = False\n        return out\n\n\n# Preserve the best priced own order(s) when the rival retreats one tick.\n_FarOnlyBase = _IncumbentStrategy\n\nclass Strategy(_FarOnlyBase):\n    def __init__(self):\n        super().__init__()\n        self._retreat_previous = (None, None)\n\n    def on_step(self, state):\n        bid = state.competitor_best_bid_ticks\n        ask = state.competitor_best_ask_ticks\n        old_bid, old_ask = self._retreat_previous\n        self._retreat_previous = (bid, ask)\n\n        # Capture order tracking before the base strategy can cancel a front order.\n        front = {}\n        for side in (Side.BUY, Side.SELL):\n            orders = [o for o in state.own_orders if o.side is side]\n            if orders:\n                tick = max(o.price_ticks for o in orders) if side is Side.BUY else min(o.price_ticks for o in orders)\n                front[side] = {o.order_id for o in orders if o.price_ticks == tick}\n            else:\n                front[side] = set()\n        ahead_before = self.ahead.copy()\n        res_before = self.res.copy()\n        actions = super().on_step(state)\n        if self.s not in (2, 3):\n            return actions\n        blocked = set()\n        if bid is not None and old_bid is not None and bid == old_bid - 1:\n            blocked.add(Side.BUY)\n        if ask is not None and old_ask is not None and ask == old_ask + 1:\n            blocked.add(Side.SELL)\n        if not blocked:\n            return actions\n\n        keep = set().union(*(front[side] for side in blocked))\n        out = []\n        for action in actions:\n            if isinstance(action, CancelOrder) and action.order_id in keep:\n                if action.order_id in ahead_before:\n                    self.ahead.add(action.order_id)\n                if action.order_id in res_before:\n                    self.res[action.order_id] = res_before[action.order_id]\n                continue\n            if True and isinstance(action, PlaceOrder) and action.side in blocked:\n                self.ahead.discard(action.client_order_id)\n                self.res.pop(action.client_order_id, None)\n                continue\n            out.append(action)\n        canceled = {a.order_id for a in out if isinstance(a, CancelOrder)}\n        out.extend(CancelOrder(o.order_id) for o in state.own_orders\n                   if o.side in blocked and o.order_id not in keep and o.order_id not in canceled)\n        if True:\n            if Side.BUY in blocked:\n                self.pb.clear()\n            if Side.SELL in blocked:\n                self.pa.clear()\n                self.last_quote_exposed = False\n        else:\n            # Retaining front collateral invalidates the base strategy's\n            # free-cash estimate. Admit placements only while funded.\n            old = {o.order_id: o for o in state.own_orders}\n            cancels = [a for a in out if isinstance(a, CancelOrder)]\n            places = [a for a in out if isinstance(a, PlaceOrder)]\n            free = state.free_cash\n            for a in cancels:\n                o = old[a.order_id]\n                if o.side is Side.BUY:\n                    free += o.price_ticks * o.remaining_quantity / 100.0\n                else:\n                    free += (1 - o.price_ticks / 100.0) * min(res_before.get(o.order_id, 0.0), o.remaining_quantity)\n            admitted = []\n            for a in places:\n                unit = a.price_ticks / 100.0 if a.side is Side.BUY else 1 - a.price_ticks / 100.0\n                qty = min(a.quantity, math.floor(max(0.0, free - 1e-7) / unit * 100.0 + 1e-9) / 100.0)\n                if qty < 0.01:\n                    self.ahead.discard(a.client_order_id)\n                    self.res.pop(a.client_order_id, None)\n                    if a.quantity == 0.01:\n                        (self.pb if a.side is Side.BUY else self.pa).discard(a.price_ticks)\n                    continue\n                if qty < a.quantity:\n                    a = PlaceOrder(side=a.side, price_ticks=a.price_ticks,\n                                   quantity=qty, client_order_id=a.client_order_id)\n                    if a.side is Side.SELL and a.client_order_id in self.res:\n                        self.res[a.client_order_id] = min(self.res[a.client_order_id], qty)\n                admitted.append(a)\n                free -= unit * qty\n            out = cancels + admitted\n        return out\n","code_sha256":"f135c96276a0bc55e504081a3928c4c03cf525b8b4888acae408e5d0a2c46957","comparator_sha256":"3c07bdcd221ac25729c3ebc92b21ac9e2014510ecb85816c4391ed81e933291f","target_spreads":[2,3],"tuning":{"seeds":{"start":330000,"end":330199,"n":200},"selected":"far_suppress","variants":{"far_suppress":{"code_sha256":"f135c96276a0bc55e504081a3928c4c03cf525b8b4888acae408e5d0a2c46957","target":{"n":106,"sum_d":4.321274817600035,"sum_d2":16.858004863048965,"mean_diff":0.04076674356226448,"se":0.03871456651494439,"comparator_mean":99.0873714502934,"candidate_mean":99.12813819385566,"retail_diff":0.007723673534905869,"arb_diff":0.03304307002830189},"overall":{"n":200,"sum_d":4.321274817600035,"sum_d2":16.858004863048965,"mean_diff":0.021606374088000174,"se":0.020523694960807925,"comparator_mean":97.4672213329115,"candidate_mean":97.48882770699949,"retail_diff":0.00409354697350011,"arb_diff":0.017512827115},"by_spread":{"1":{"n":54,"sum_d":0.0,"sum_d2":0.0,"mean_diff":0.0,"se":0.0,"comparator_mean":46.182844338938885,"candidate_mean":46.182844338938885,"retail_diff":0.0,"arb_diff":0.0},"2":{"n":57,"sum_d":3.384897674599962,"sum_d2":15.981202709115987,"mean_diff":0.059384169729823896,"se":0.07031123382839782,"comparator_mean":87.23571902150526,"candidate_mean":87.2951031912351,"retail_diff":-0.0015818007175431902,"arb_diff":0.060965970449122754},"3":{"n":49,"sum_d":0.9363771430000725,"sum_d2":0.8768021539329781,"mean_diff":0.019109737612246377,"se":0.019109737612246377,"comparator_mean":112.87398754092447,"candidate_mean":112.89309727853674,"retail_diff":0.01854840888979559,"arb_diff":0.0005613287224490454},"4":{"n":40,"sum_d":0.0,"sum_d2":0.0,"mean_diff":0.0,"se":0.0,"comparator_mean":162.4077324637125,"candidate_mean":162.4077324637125,"retail_diff":0.0,"arb_diff":0.0}}},"far_place":{"code_sha256":"2563818fb550ab21b8da220c417e4f40d00506560b0ee2e4c637562353f61705","target":{"n":106,"sum_d":-91.5342973980999,"sum_d2":1495.5836095177362,"mean_diff":-0.8635311075292443,"se":0.35675246001624283,"comparator_mean":99.0873714502934,"candidate_mean":98.22384034276415,"retail_diff":0.2615986946160407,"arb_diff":-1.125129802138679},"overall":{"n":200,"sum_d":-91.5342973980999,"sum_d2":1495.5836095177362,"mean_diff":-0.4576714869904995,"se":0.19111488372660065,"comparator_mean":97.4672213329115,"candidate_mean":97.00954984592099,"retail_diff":0.13864730814650156,"arb_diff":-0.5963187951334998},"by_spread":{"1":{"n":54,"sum_d":0.0,"sum_d2":0.0,"mean_diff":0.0,"se":0.0,"comparator_mean":46.182844338938885,"candidate_mean":46.182844338938885,"retail_diff":0.0,"arb_diff":0.0},"2":{"n":57,"sum_d":-50.630137090099986,"sum_d2":684.3444313463146,"mean_diff":-0.8882480191245612,"se":0.4475540292946244,"comparator_mean":87.23571902150526,"candidate_mean":86.3474710023807,"retail_diff":0.01092078674736996,"arb_diff":-0.8991688059228073},"3":{"n":49,"sum_d":-40.9041603079999,"sum_d2":811.2391781714215,"mean_diff":-0.8347787817959164,"se":0.5748015233684011,"comparator_mean":112.87398754092447,"candidate_mean":112.03920875912857,"retail_diff":0.553203607851025,"arb_diff":-1.3879823895734686},"4":{"n":40,"sum_d":0.0,"sum_d2":0.0,"mean_diff":0.0,"se":0.0,"comparator_mean":162.4077324637125,"candidate_mean":162.4077324637125,"retail_diff":0.0,"arb_diff":0.0}}}}},"paired":{"seeds":{"start":440000,"end":440499,"n":500},"n":500,"complete":true,"missing_seeds":[],"overall":{"n":500,"sum_d":0.8219705217000506,"sum_d2":16.237193780206596,"mean_diff":0.0016439410434001011,"se":0.008066815795012264,"comparator_mean":101.4369248623788,"candidate_mean":101.4385688034222,"retail_diff":-0.0007178855157999919,"arb_diff":0.002361826559199983},"by_spread":{"1":{"n":142,"sum_d":0.0,"sum_d2":0.0,"mean_diff":0.0,"se":0.0,"comparator_mean":28.7146791778493,"candidate_mean":28.7146791778493,"retail_diff":0.0,"arb_diff":0.0},"2":{"n":110,"sum_d":3.0714752703000254,"sum_d2":11.17692216623276,"mean_diff":0.027922502457272957,"se":0.03041437328999315,"comparator_mean":88.78927784058273,"candidate_mean":88.81720034304,"retail_diff":-0.003263115980909054,"arb_diff":0.031185618438181704},"3":{"n":119,"sum_d":-2.249504748599975,"sum_d2":5.060271613973836,"mean_diff":-0.018903401248739283,"se":0.018903401248739286,"comparator_mean":143.37780997585293,"candidate_mean":143.35890657460422,"retail_diff":0.0,"arb_diff":-0.018903401248739463},"4":{"n":129,"sum_d":0.0,"sum_d2":0.0,"mean_diff":0.0,"se":0.0,"comparator_mean":153.5829305298,"candidate_mean":153.5829305298,"retail_diff":0.0,"arb_diff":0.0}}},"failures":[],"check_values":{"310000":17.5126554022,"310001":20.6298693268,"310002":2.3903113616,"310003":248.006347259},"python_version":"3.12.3","seconds_per_simulation":0.42222626020526516}
