[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6J0PP0YR5NT5X2HJ98HR588":3,"skill-same:01M6J0PP0YR5NT5X2HJ98HR588":71},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":43,"linkOnly":44,"markdownContent":45,"markdownBody":46,"frontMatter":47,"refName":48,"commitSha":49,"skillDirectory":50,"forksCount":51,"repositoryHtmlUrl":52,"repositoryHomepageUrl":6,"ownerHtmlUrl":53,"ownerBlogUrl":54,"ownerDescription":55,"updatedAt":56,"install":57,"resources":70},"01M6J0PP0YR5NT5X2HJ98HR588","slippage-budget-enforcement",null,"Use when executing any taker (Ioc or market) order on HyperLiquid to calculate the maximum allowable slippage budget, enforce price tolerance before submission, detect post-fill slippage violations, and abort or resize orders that would exceed the session slippage cap.","enuno\u002Fhyperliquid-trading-firm","enuno","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6727752?v=4","01M6J09HF6Y74150F7PEMC446X","Elvis Nuno","01M6J09HKK0YMKE39JXT8JT8VM",1,"GPL-3.0","https:\u002F\u002Fgithub.com\u002Fenuno\u002Fhyperliquid-trading-firm\u002Fblob\u002Fmain\u002Fmulticlaw\u002Fmetaclaw\u002Fskills\u002Fexecution\u002Fslippage-budget-enforcement\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000040","财务","PROFESSION","适用职业",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42],"slippage budget enforcement","Budget","enforcement","slippage","hyperliquid","fill","tolerance","detect","post","price","orders","enforce","agentic","cap","Market","use","session","calculate","ioc","2026-11-10 10:12:30",false,"---\nname: slippage-budget-enforcement\ndescription: Use when executing any taker (Ioc or market) order on HyperLiquid to calculate the maximum allowable slippage budget, enforce price tolerance before submission, detect post-fill slippage violations, and abort or resize orders that would exceed the session slippage cap.\ncategory: agentic\n---\n\n# Slippage Budget Enforcement\n\n## When This Skill Activates\n\nApply this skill **on every taker order** (`tif: \"Ioc\"` or market) before\nsubmission and again after fill confirmation. Also apply when:\n\n- A maker (`Alo`) order has been rejected and taker execution is being\n  considered as fallback\n- A cascade exit or kill-switch triggers a market order and a worst-case\n  slippage estimate is needed for position sizing the exit\n- Session-level slippage has accumulated and a new taker order would\n  breach the session cap\n- Book depth has thinned significantly and the expected fill price for\n  a given size must be estimated before committing\n\n---\n\n## Core Principle\n\nSlippage on taker orders is **not random noise** — it is a predictable\nfunction of order size relative to available book depth. Large taker\norders walk the book, consuming successive price levels and filling at\nproggressively worse prices. On HyperLiquid’s thin-book perp markets,\na $50k market order in low-liquidity conditions can incur 10–20 bps of\nslippage — equivalent to paying taker fee *twice*.\n\n> **Rule**: Before submitting any taker order, simulate the fill by\n> walking the live order book. If the simulated slippage exceeds the\n> order’s slippage budget, either reduce order size or abort.\n> Never submit a taker order blind.\n\n---\n\n## Slippage Budget Framework\n\n### Per-Order Slippage Budget\n\nThe per-order slippage budget is derived from the trade’s expected edge\nminus the taker fee already accounted for in `maker-order-preference-fee-reduction`:\n\n```python\ndef per_order_slippage_budget_bps(\n    expected_move_bps: float,       # from strategy signal\n    taker_fee_bps: float = 3.5,     # base tier: 0.035% = 3.5 bps\n    min_net_edge_bps: float = 2.0,  # minimum edge to keep after all costs\n) -> float:\n    \"\"\"\n    Maximum slippage that still leaves a minimum net edge after\n    taker fee and slippage are both deducted.\n    \"\"\"\n    budget = expected_move_bps - taker_fee_bps - min_net_edge_bps\n    return max(0.0, budget)  # 0.0 = no slippage tolerance; do not trade\n\n# Example: expected move = 15 bps, taker fee = 3.5 bps, min edge = 2 bps\n# slippage_budget = 15 - 3.5 - 2.0 = 9.5 bps\n#\n# Example: expected move = 8 bps\n# slippage_budget = 8 - 3.5 - 2.0 = 2.5 bps  (very tight; consider maker entry)\n#\n# Example: expected move = 5 bps\n# slippage_budget = 5 - 3.5 - 2.0 = -0.5 → clamped to 0.0\n# → Do not use taker. Taker fee alone consumes more than expected move minus min edge.\n```\n\n### Session Slippage Cap\n\nBeyond per-order budgets, enforce a hard **session-level slippage cap**\nto prevent cumulative slippage from silently eroding P&L:\n\n```python\nSESSION_SLIPPAGE_CAP_BPS = 20.0   # total across all taker fills in session\nSESSION_SLIPPAGE_WARN_BPS = 15.0  # warning threshold: reduce taker aggression\n\n# Session tracking (in-memory; reset at session start):\nclass SlippageTracker:\n    def __init__(self):\n        self.session_slippage_bps: float = 0.0\n        self.taker_fills: list = []\n\n    def record_fill(self, expected_price: float, fill_price: float,\n                    side: str, notional_usd: float) -> float:\n        if side == \"buy\":\n            slippage_bps = (fill_price - expected_price) \u002F expected_price * 10000\n        else:\n            slippage_bps = (expected_price - fill_price) \u002F expected_price * 10000\n        slippage_bps = max(0.0, slippage_bps)  # only count adverse slippage\n        self.session_slippage_bps += slippage_bps\n        self.taker_fills.append({\n            \"expected_price\": expected_price,\n            \"fill_price\": fill_price,\n            \"slippage_bps\": slippage_bps,\n            \"notional_usd\": notional_usd,\n        })\n        return slippage_bps\n\n    def can_place_taker(self, estimated_slippage_bps: float) -> tuple[bool, str]:\n        projected = self.session_slippage_bps + estimated_slippage_bps\n        if projected >= SESSION_SLIPPAGE_CAP_BPS:\n            return False, \"session_cap_breached\"\n        if self.session_slippage_bps >= SESSION_SLIPPAGE_WARN_BPS:\n            return True, \"warning_reduce_size\"\n        return True, \"ok\"\n```\n\n---\n\n## Book Walk Simulation\n\nBefore submitting any taker order, simulate the fill by walking the\nlive `l2Book` to estimate expected fill price and slippage:\n\n```python\ndef simulate_taker_fill(\n    l2book: dict,\n    side: str,           # \"buy\" consumes asks; \"sell\" consumes bids\n    order_size_usd: float,\n    mid_price: float,\n) -> dict:\n    \"\"\"\n    Walk the order book to estimate average fill price and slippage\n    for a taker order of order_size_usd notional.\n    Returns fill estimate with slippage_bps and fill_coverage_pct.\n    \"\"\"\n    levels = l2book[\"levels\"][1] if side == \"buy\" else l2book[\"levels\"][0]\n    # levels format: [{\"px\": price_str, \"sz\": size_str, \"n\": num_orders}, ...]\n    # buy: walk asks ascending; sell: walk bids descending\n\n    remaining_usd = order_size_usd\n    total_cost    = 0.0\n    total_filled  = 0.0\n\n    for level in levels:\n        level_px   = float(level[\"px\"])\n        level_sz   = float(level[\"sz\"])   # size in base asset\n        level_usd  = level_sz * level_px\n\n        fill_usd   = min(remaining_usd, level_usd)\n        fill_sz    = fill_usd \u002F level_px\n\n        total_cost   += fill_sz * level_px\n        total_filled += fill_sz\n        remaining_usd -= fill_usd\n\n        if remaining_usd \u003C= 0:\n            break\n\n    if total_filled == 0:\n        return {\"feasible\": False, \"reason\": \"no_book_depth\"}\n\n    avg_fill_price = total_cost \u002F total_filled\n    fill_coverage  = (order_size_usd - remaining_usd) \u002F order_size_usd\n\n    if side == \"buy\":\n        slippage_bps = (avg_fill_price - mid_price) \u002F mid_price * 10000\n    else:\n        slippage_bps = (mid_price - avg_fill_price) \u002F mid_price * 10000\n\n    return {\n        \"feasible\": fill_coverage >= 0.95,   # require 95% fill or reject\n        \"avg_fill_price\": avg_fill_price,\n        \"slippage_bps\": max(0.0, slippage_bps),\n        \"fill_coverage_pct\": fill_coverage * 100,\n        \"unfilled_usd\": remaining_usd,\n        \"levels_consumed\": sum(1 for _ in levels),  # approximate\n    }\n```\n\n### Interpreting Book Walk Results\n\n| Result | Condition | Action |\n|---|---|---|\n| `feasible: True`, slippage ≤ budget | Full fill, within budget | Submit order as sized |\n| `feasible: True`, slippage > budget | Full fill but too costly | Reduce size until slippage ≤ budget |\n| `feasible: False`, coverage \u003C 95% | Insufficient depth | Reduce size to available depth × 0.80 |\n| `feasible: False`, no depth | Book empty \u002F extreme cascade | Abort. Use `liquidation-cascade-risk` protocol |\n\n---\n\n## Size Reduction to Meet Slippage Budget\n\nWhen the simulated slippage exceeds budget, binary-search for the\nmaximum order size that stays within budget:\n\n```python\ndef max_size_within_budget(\n    l2book: dict,\n    side: str,\n    mid_price: float,\n    slippage_budget_bps: float,\n    initial_size_usd: float,\n    min_size_usd: float = 100.0,\n) -> float:\n    \"\"\"\n    Binary search for largest order size whose simulated slippage\n    is \u003C= slippage_budget_bps. Returns 0.0 if min_size_usd also exceeds budget.\n    \"\"\"\n    lo, hi = min_size_usd, initial_size_usd\n    for _ in range(12):   # 12 iterations -> 0.02% precision\n        mid_size = (lo + hi) \u002F 2\n        result = simulate_taker_fill(l2book, side, mid_size, mid_price)\n        if not result[\"feasible\"] or result[\"slippage_bps\"] > slippage_budget_bps:\n            hi = mid_size\n        else:\n            lo = mid_size\n    # Final check at lo:\n    result = simulate_taker_fill(l2book, side, lo, mid_price)\n    if not result[\"feasible\"] or result[\"slippage_bps\"] > slippage_budget_bps:\n        return 0.0   # even minimum size exceeds budget; abort\n    return lo\n```\n\n---\n\n## Pre-Submission Enforcement Checklist\n\nRun this checklist **in order** before every taker order submission:\n\n```\n1. Compute per-order slippage budget:\n   budget_bps = per_order_slippage_budget_bps(expected_move_bps)\n   └── budget_bps == 0.0?  → ABORT. Taker fee alone kills the edge.\n\n2. Check session cap:\n   can_place, status = tracker.can_place_taker(estimated_slippage_bps)\n   ├── can_place == False  → ABORT. Session slippage cap reached.\n   └── status == \"warning_reduce_size\"  → Halve order size before continuing.\n\n3. Simulate book walk:\n   sim = simulate_taker_fill(l2book, side, order_size_usd, mid_price)\n   ├── sim.feasible == False  → Reduce size per depth or ABORT.\n   └── sim.slippage_bps > budget_bps  → Run max_size_within_budget().\n                                        ├── adjusted_size > 0  → Continue at adjusted size.\n                                        └── adjusted_size == 0  → ABORT.\n\n4. Submit order at adjusted_size with price_tolerance:\n   worst_acceptable_price = mid_price ± (budget_bps \u002F 10000 * mid_price)\n   # Use this as the limit price on an Ioc order to cap worst-case fill:\n   # {\"t\": {\"limit\": {\"tif\": \"Ioc\"}}, \"p\": worst_acceptable_price, ...}\n   # Do NOT use pure market orders unless cascade\u002Fkill-switch override.\n\n5. Post-fill: record actual slippage via tracker.record_fill()\n   └── actual_slippage_bps > budget_bps?  → Log violation. Flag for review.\n```\n\n---\n\n## Defensive Override: Cascade and Kill-Switch Exits\n\nWhen a **CRITICAL cascade exit** or **kill-switch** fires, the slippage\nbudget framework is **suspended** — fill certainty takes absolute\npriority over cost:\n\n```python\ndef submit_defensive_exit(\n    side: str,\n    size_usd: float,\n    mid_price: float,\n    reason: str,   # \"cascade_critical\", \"kill_switch\", \"stop_breach\"\n) -> dict:\n    # No budget check. No book walk. Submit market order immediately.\n    order = {\n        \"orders\": [{\n            \"a\": asset_index,\n            \"b\": side == \"buy\",\n            \"p\": \"0\",       # market order price field (ignored)\n            \"s\": str(size_base_asset),\n            \"r\": True,      # reduce-only\n            \"t\": {\"market\": {}}\n        }],\n        \"grouping\": \"na\"\n    }\n    # Log defensive override for RL replay buffer:\n    log_event({\n        \"event\": \"defensive_exit\",\n        \"reason\": reason,\n        \"size_usd\": size_usd,\n        \"slippage_budget_suspended\": True,\n        \"estimated_slippage_bps\": simulate_taker_fill(\n            l2book, side, size_usd, mid_price\n        ).get(\"slippage_bps\", \"unknown\"),\n    })\n    return order\n```\n\nLog the estimated slippage **even on defensive exits** so the RL replay\nbuffer learns the true cost of cascade conditions and can incorporate\nthat into future position-sizing decisions.\n\n---\n\n## Slippage by Asset and Condition Reference\n\nTypical observed slippage ranges on HyperLiquid for a **$10k taker\norder** under different book conditions (verify from live fills):\n\n| Asset | Normal Book | Thin Book | During Cascade |\n|---|---|---|---|\n| BTC | 0.2–0.5 bps | 1–3 bps | 5–20 bps |\n| ETH | 0.3–0.8 bps | 1.5–4 bps | 8–25 bps |\n| SOL | 0.5–1.5 bps | 3–8 bps | 15–40 bps |\n| Mid-cap alts | 1–3 bps | 5–15 bps | 20–100+ bps |\n\n> These are **illustrative estimates**, not guarantees. Always use the\n> live book walk simulation for actual order sizing. Slippage during\n> cascades can exceed these ranges significantly.\n\n---\n\n## Failure Modes to Avoid\n\n- **Submitting market orders without book walk**: Market orders on thin\n  books can fill 10–50 bps worse than expected. Even for defensive exits,\n  estimate the slippage and log it — the data informs future sizing.\n- **Setting slippage tolerance as a fixed percentage**: A fixed 0.1%\n  tolerance ignores current book depth, asset liquidity, and order size.\n  Slippage tolerance must be computed per-order from the budget framework.\n- **Reusing a stale book walk result**: The l2Book snapshot used for\n  simulation must be fetched **at submission time**, not cached from the\n  last polling cycle. In volatile markets, book depth changes in \u003C 1s.\n- **Not splitting large taker orders**: If `max_size_within_budget()`\n  returns a size much smaller than the target, consider splitting into\n  multiple smaller taker orders spaced 500ms–1s apart to allow the\n  book to replenish between fills. Never send all size simultaneously\n  against a thin book.\n- **Ignoring `fill_coverage_pct`**: A simulated fill that only covers\n  70% of the order size will leave 30% unfilled as `Ioc` remainder.\n  That remainder may need a separate maker order to complete, changing\n  the execution plan and cost model.\n- **Double-counting slippage and taker fee**: Slippage (adverse price\n  movement through the book) and taker fee (exchange charge on notional)\n  are separate costs. The slippage budget framework accounts for both\n  independently. Do not lump them together in a single \"cost\" estimate.\n\n---\n\n## Integration with Other Skills\n\n- **`maker-order-preference-fee-reduction`** (execution\u002F): Determines\n  *whether* taker execution is warranted. This skill governs *how much*\n  slippage is acceptable once taker is chosen. Always run in sequence.\n- **`limit-offset-bps-calculation`** (execution\u002F): Governs the maker\n  path. If this skill’s budget check returns `0.0` (taker not viable),\n  fall back to that skill to place an `Alo` limit instead.\n- **`liquidation-cascade-risk`** (regime-detection\u002F): Cascade CRITICAL\n  overrides this skill’s budget enforcement. Also provides `book_fragility`\n  which sets the expectation for how bad slippage will be before the\n  book walk is run.\n- **`kelly-position-sizing-perps`** (risk\u002F): Position size output from\n  Kelly sizing is the `initial_size_usd` input to `max_size_within_budget()`.\n  If the book cannot absorb the Kelly size within the slippage budget,\n  the executed size must be reduced; the risk model must be informed of\n  the actual executed size for exposure tracking.\n\n---\n\n## Audit JSONL Schema\n\n```json\n{\n  \"event\": \"taker_order_slippage_check\",\n  \"asset\": \"SOL\",\n  \"timestamp_utc\": \"2026-04-07T22:00:00Z\",\n  \"side\": \"sell\",\n  \"target_size_usd\": 25000,\n  \"expected_move_bps\": 18.0,\n  \"taker_fee_bps\": 3.5,\n  \"slippage_budget_bps\": 12.5,\n  \"book_walk_slippage_bps\": 7.2,\n  \"book_walk_coverage_pct\": 100.0,\n  \"within_budget\": true,\n  \"adjusted_size_usd\": 25000,\n  \"worst_acceptable_price\": 138.143,\n  \"session_slippage_bps_before\": 4.1,\n  \"session_slippage_cap_bps\": 20.0,\n  \"defensive_override\": false,\n  \"order_result\": \"filled\",\n  \"actual_fill_price\": 138.155,\n  \"actual_slippage_bps\": 6.8,\n  \"budget_violation\": false\n}\n```\n\n---\n\n## Quick Decision Tree\n\n```\nTaker order needed — enforce slippage budget:\n│\n├── Is this a DEFENSIVE EXIT (cascade\u002Fkill-switch\u002Fstop breach)?\n│     └── YES → Submit market order. Log estimated slippage. Skip budget checks.\n│\n└── Normal taker execution path:\n      │\n      ├── 1. budget = per_order_slippage_budget_bps(expected_move)\n      │         └── budget == 0? → ABORT. Use Alo instead.\n      │\n      ├── 2. can_place, status = tracker.can_place_taker(estimated_slippage)\n      │         ├── can_place False? → ABORT. Session cap hit.\n      │         └── status \"warning\"? → Halve size. Continue.\n      │\n      ├── 3. sim = simulate_taker_fill(l2book, side, size, mid)\n      │         ├── sim.slippage > budget? → max_size_within_budget()\n      │         │         ├── adjusted > 0? → Use adjusted size.\n      │         │         └── adjusted == 0? → ABORT. Use Alo.\n      │         └── sim.feasible False? → Reduce to depth × 0.80. Re-simulate.\n      │\n      └── 4. Submit Ioc at worst_acceptable_price.\n               Post-fill: tracker.record_fill(). Log audit event.\n```\n","# Slippage Budget Enforcement\n\n## When This Skill Activates\n\nApply this skill **on every taker order** (`tif: \"Ioc\"` or market) before\nsubmission and again after fill confirmation. Also apply when:\n\n- A maker (`Alo`) order has been rejected and taker execution is being\n  considered as fallback\n- A cascade exit or kill-switch triggers a market order and a worst-case\n  slippage estimate is needed for position sizing the exit\n- Session-level slippage has accumulated and a new taker order would\n  breach the session cap\n- Book depth has thinned significantly and the expected fill price for\n  a given size must be estimated before committing\n\n---\n\n## Core Principle\n\nSlippage on taker orders is **not random noise** — it is a predictable\nfunction of order size relative to available book depth. Large taker\norders walk the book, consuming successive price levels and filling at\nproggressively worse prices. On HyperLiquid’s thin-book perp markets,\na $50k market order in low-liquidity conditions can incur 10–20 bps of\nslippage — equivalent to paying taker fee *twice*.\n\n> **Rule**: Before submitting any taker order, simulate the fill by\n> walking the live order book. If the simulated slippage exceeds the\n> order’s slippage budget, either reduce order size or abort.\n> Never submit a taker order blind.\n\n---\n\n## Slippage Budget Framework\n\n### Per-Order Slippage Budget\n\nThe per-order slippage budget is derived from the trade’s expected edge\nminus the taker fee already accounted for in `maker-order-preference-fee-reduction`:\n\n```python\ndef per_order_slippage_budget_bps(\n    expected_move_bps: float,       # from strategy signal\n    taker_fee_bps: float = 3.5,     # base tier: 0.035% = 3.5 bps\n    min_net_edge_bps: float = 2.0,  # minimum edge to keep after all costs\n) -> float:\n    \"\"\"\n    Maximum slippage that still leaves a minimum net edge after\n    taker fee and slippage are both deducted.\n    \"\"\"\n    budget = expected_move_bps - taker_fee_bps - min_net_edge_bps\n    return max(0.0, budget)  # 0.0 = no slippage tolerance; do not trade\n\n# Example: expected move = 15 bps, taker fee = 3.5 bps, min edge = 2 bps\n# slippage_budget = 15 - 3.5 - 2.0 = 9.5 bps\n#\n# Example: expected move = 8 bps\n# slippage_budget = 8 - 3.5 - 2.0 = 2.5 bps  (very tight; consider maker entry)\n#\n# Example: expected move = 5 bps\n# slippage_budget = 5 - 3.5 - 2.0 = -0.5 → clamped to 0.0\n# → Do not use taker. Taker fee alone consumes more than expected move minus min edge.\n```\n\n### Session Slippage Cap\n\nBeyond per-order budgets, enforce a hard **session-level slippage cap**\nto prevent cumulative slippage from silently eroding P&L:\n\n```python\nSESSION_SLIPPAGE_CAP_BPS = 20.0   # total across all taker fills in session\nSESSION_SLIPPAGE_WARN_BPS = 15.0  # warning threshold: reduce taker aggression\n\n# Session tracking (in-memory; reset at session start):\nclass SlippageTracker:\n    def __init__(self):\n        self.session_slippage_bps: float = 0.0\n        self.taker_fills: list = []\n\n    def record_fill(self, expected_price: float, fill_price: float,\n                    side: str, notional_usd: float) -> float:\n        if side == \"buy\":\n            slippage_bps = (fill_price - expected_price) \u002F expected_price * 10000\n        else:\n            slippage_bps = (expected_price - fill_price) \u002F expected_price * 10000\n        slippage_bps = max(0.0, slippage_bps)  # only count adverse slippage\n        self.session_slippage_bps += slippage_bps\n        self.taker_fills.append({\n            \"expected_price\": expected_price,\n            \"fill_price\": fill_price,\n            \"slippage_bps\": slippage_bps,\n            \"notional_usd\": notional_usd,\n        })\n        return slippage_bps\n\n    def can_place_taker(self, estimated_slippage_bps: float) -> tuple[bool, str]:\n        projected = self.session_slippage_bps + estimated_slippage_bps\n        if projected >= SESSION_SLIPPAGE_CAP_BPS:\n            return False, \"session_cap_breached\"\n        if self.session_slippage_bps >= SESSION_SLIPPAGE_WARN_BPS:\n            return True, \"warning_reduce_size\"\n        return True, \"ok\"\n```\n\n---\n\n## Book Walk Simulation\n\nBefore submitting any taker order, simulate the fill by walking the\nlive `l2Book` to estimate expected fill price and slippage:\n\n```python\ndef simulate_taker_fill(\n    l2book: dict,\n    side: str,           # \"buy\" consumes asks; \"sell\" consumes bids\n    order_size_usd: float,\n    mid_price: float,\n) -> dict:\n    \"\"\"\n    Walk the order book to estimate average fill price and slippage\n    for a taker order of order_size_usd notional.\n    Returns fill estimate with slippage_bps and fill_coverage_pct.\n    \"\"\"\n    levels = l2book[\"levels\"][1] if side == \"buy\" else l2book[\"levels\"][0]\n    # levels format: [{\"px\": price_str, \"sz\": size_str, \"n\": num_orders}, ...]\n    # buy: walk asks ascending; sell: walk bids descending\n\n    remaining_usd = order_size_usd\n    total_cost    = 0.0\n    total_filled  = 0.0\n\n    for level in levels:\n        level_px   = float(level[\"px\"])\n        level_sz   = float(level[\"sz\"])   # size in base asset\n        level_usd  = level_sz * level_px\n\n        fill_usd   = min(remaining_usd, level_usd)\n        fill_sz    = fill_usd \u002F level_px\n\n        total_cost   += fill_sz * level_px\n        total_filled += fill_sz\n        remaining_usd -= fill_usd\n\n        if remaining_usd \u003C= 0:\n            break\n\n    if total_filled == 0:\n        return {\"feasible\": False, \"reason\": \"no_book_depth\"}\n\n    avg_fill_price = total_cost \u002F total_filled\n    fill_coverage  = (order_size_usd - remaining_usd) \u002F order_size_usd\n\n    if side == \"buy\":\n        slippage_bps = (avg_fill_price - mid_price) \u002F mid_price * 10000\n    else:\n        slippage_bps = (mid_price - avg_fill_price) \u002F mid_price * 10000\n\n    return {\n        \"feasible\": fill_coverage >= 0.95,   # require 95% fill or reject\n        \"avg_fill_price\": avg_fill_price,\n        \"slippage_bps\": max(0.0, slippage_bps),\n        \"fill_coverage_pct\": fill_coverage * 100,\n        \"unfilled_usd\": remaining_usd,\n        \"levels_consumed\": sum(1 for _ in levels),  # approximate\n    }\n```\n\n### Interpreting Book Walk Results\n\n| Result | Condition | Action |\n|---|---|---|\n| `feasible: True`, slippage ≤ budget | Full fill, within budget | Submit order as sized |\n| `feasible: True`, slippage > budget | Full fill but too costly | Reduce size until slippage ≤ budget |\n| `feasible: False`, coverage \u003C 95% | Insufficient depth | Reduce size to available depth × 0.80 |\n| `feasible: False`, no depth | Book empty \u002F extreme cascade | Abort. Use `liquidation-cascade-risk` protocol |\n\n---\n\n## Size Reduction to Meet Slippage Budget\n\nWhen the simulated slippage exceeds budget, binary-search for the\nmaximum order size that stays within budget:\n\n```python\ndef max_size_within_budget(\n    l2book: dict,\n    side: str,\n    mid_price: float,\n    slippage_budget_bps: float,\n    initial_size_usd: float,\n    min_size_usd: float = 100.0,\n) -> float:\n    \"\"\"\n    Binary search for largest order size whose simulated slippage\n    is \u003C= slippage_budget_bps. Returns 0.0 if min_size_usd also exceeds budget.\n    \"\"\"\n    lo, hi = min_size_usd, initial_size_usd\n    for _ in range(12):   # 12 iterations -> 0.02% precision\n        mid_size = (lo + hi) \u002F 2\n        result = simulate_taker_fill(l2book, side, mid_size, mid_price)\n        if not result[\"feasible\"] or result[\"slippage_bps\"] > slippage_budget_bps:\n            hi = mid_size\n        else:\n            lo = mid_size\n    # Final check at lo:\n    result = simulate_taker_fill(l2book, side, lo, mid_price)\n    if not result[\"feasible\"] or result[\"slippage_bps\"] > slippage_budget_bps:\n        return 0.0   # even minimum size exceeds budget; abort\n    return lo\n```\n\n---\n\n## Pre-Submission Enforcement Checklist\n\nRun this checklist **in order** before every taker order submission:\n\n```\n1. Compute per-order slippage budget:\n   budget_bps = per_order_slippage_budget_bps(expected_move_bps)\n   └── budget_bps == 0.0?  → ABORT. Taker fee alone kills the edge.\n\n2. Check session cap:\n   can_place, status = tracker.can_place_taker(estimated_slippage_bps)\n   ├── can_place == False  → ABORT. Session slippage cap reached.\n   └── status == \"warning_reduce_size\"  → Halve order size before continuing.\n\n3. Simulate book walk:\n   sim = simulate_taker_fill(l2book, side, order_size_usd, mid_price)\n   ├── sim.feasible == False  → Reduce size per depth or ABORT.\n   └── sim.slippage_bps > budget_bps  → Run max_size_within_budget().\n                                        ├── adjusted_size > 0  → Continue at adjusted size.\n                                        └── adjusted_size == 0  → ABORT.\n\n4. Submit order at adjusted_size with price_tolerance:\n   worst_acceptable_price = mid_price ± (budget_bps \u002F 10000 * mid_price)\n   # Use this as the limit price on an Ioc order to cap worst-case fill:\n   # {\"t\": {\"limit\": {\"tif\": \"Ioc\"}}, \"p\": worst_acceptable_price, ...}\n   # Do NOT use pure market orders unless cascade\u002Fkill-switch override.\n\n5. Post-fill: record actual slippage via tracker.record_fill()\n   └── actual_slippage_bps > budget_bps?  → Log violation. Flag for review.\n```\n\n---\n\n## Defensive Override: Cascade and Kill-Switch Exits\n\nWhen a **CRITICAL cascade exit** or **kill-switch** fires, the slippage\nbudget framework is **suspended** — fill certainty takes absolute\npriority over cost:\n\n```python\ndef submit_defensive_exit(\n    side: str,\n    size_usd: float,\n    mid_price: float,\n    reason: str,   # \"cascade_critical\", \"kill_switch\", \"stop_breach\"\n) -> dict:\n    # No budget check. No book walk. Submit market order immediately.\n    order = {\n        \"orders\": [{\n            \"a\": asset_index,\n            \"b\": side == \"buy\",\n            \"p\": \"0\",       # market order price field (ignored)\n            \"s\": str(size_base_asset),\n            \"r\": True,      # reduce-only\n            \"t\": {\"market\": {}}\n        }],\n        \"grouping\": \"na\"\n    }\n    # Log defensive override for RL replay buffer:\n    log_event({\n        \"event\": \"defensive_exit\",\n        \"reason\": reason,\n        \"size_usd\": size_usd,\n        \"slippage_budget_suspended\": True,\n        \"estimated_slippage_bps\": simulate_taker_fill(\n            l2book, side, size_usd, mid_price\n        ).get(\"slippage_bps\", \"unknown\"),\n    })\n    return order\n```\n\nLog the estimated slippage **even on defensive exits** so the RL replay\nbuffer learns the true cost of cascade conditions and can incorporate\nthat into future position-sizing decisions.\n\n---\n\n## Slippage by Asset and Condition Reference\n\nTypical observed slippage ranges on HyperLiquid for a **$10k taker\norder** under different book conditions (verify from live fills):\n\n| Asset | Normal Book | Thin Book | During Cascade |\n|---|---|---|---|\n| BTC | 0.2–0.5 bps | 1–3 bps | 5–20 bps |\n| ETH | 0.3–0.8 bps | 1.5–4 bps | 8–25 bps |\n| SOL | 0.5–1.5 bps | 3–8 bps | 15–40 bps |\n| Mid-cap alts | 1–3 bps | 5–15 bps | 20–100+ bps |\n\n> These are **illustrative estimates**, not guarantees. Always use the\n> live book walk simulation for actual order sizing. Slippage during\n> cascades can exceed these ranges significantly.\n\n---\n\n## Failure Modes to Avoid\n\n- **Submitting market orders without book walk**: Market orders on thin\n  books can fill 10–50 bps worse than expected. Even for defensive exits,\n  estimate the slippage and log it — the data informs future sizing.\n- **Setting slippage tolerance as a fixed percentage**: A fixed 0.1%\n  tolerance ignores current book depth, asset liquidity, and order size.\n  Slippage tolerance must be computed per-order from the budget framework.\n- **Reusing a stale book walk result**: The l2Book snapshot used for\n  simulation must be fetched **at submission time**, not cached from the\n  last polling cycle. In volatile markets, book depth changes in \u003C 1s.\n- **Not splitting large taker orders**: If `max_size_within_budget()`\n  returns a size much smaller than the target, consider splitting into\n  multiple smaller taker orders spaced 500ms–1s apart to allow the\n  book to replenish between fills. Never send all size simultaneously\n  against a thin book.\n- **Ignoring `fill_coverage_pct`**: A simulated fill that only covers\n  70% of the order size will leave 30% unfilled as `Ioc` remainder.\n  That remainder may need a separate maker order to complete, changing\n  the execution plan and cost model.\n- **Double-counting slippage and taker fee**: Slippage (adverse price\n  movement through the book) and taker fee (exchange charge on notional)\n  are separate costs. The slippage budget framework accounts for both\n  independently. Do not lump them together in a single \"cost\" estimate.\n\n---\n\n## Integration with Other Skills\n\n- **`maker-order-preference-fee-reduction`** (execution\u002F): Determines\n  *whether* taker execution is warranted. This skill governs *how much*\n  slippage is acceptable once taker is chosen. Always run in sequence.\n- **`limit-offset-bps-calculation`** (execution\u002F): Governs the maker\n  path. If this skill’s budget check returns `0.0` (taker not viable),\n  fall back to that skill to place an `Alo` limit instead.\n- **`liquidation-cascade-risk`** (regime-detection\u002F): Cascade CRITICAL\n  overrides this skill’s budget enforcement. Also provides `book_fragility`\n  which sets the expectation for how bad slippage will be before the\n  book walk is run.\n- **`kelly-position-sizing-perps`** (risk\u002F): Position size output from\n  Kelly sizing is the `initial_size_usd` input to `max_size_within_budget()`.\n  If the book cannot absorb the Kelly size within the slippage budget,\n  the executed size must be reduced; the risk model must be informed of\n  the actual executed size for exposure tracking.\n\n---\n\n## Audit JSONL Schema\n\n```json\n{\n  \"event\": \"taker_order_slippage_check\",\n  \"asset\": \"SOL\",\n  \"timestamp_utc\": \"2026-04-07T22:00:00Z\",\n  \"side\": \"sell\",\n  \"target_size_usd\": 25000,\n  \"expected_move_bps\": 18.0,\n  \"taker_fee_bps\": 3.5,\n  \"slippage_budget_bps\": 12.5,\n  \"book_walk_slippage_bps\": 7.2,\n  \"book_walk_coverage_pct\": 100.0,\n  \"within_budget\": true,\n  \"adjusted_size_usd\": 25000,\n  \"worst_acceptable_price\": 138.143,\n  \"session_slippage_bps_before\": 4.1,\n  \"session_slippage_cap_bps\": 20.0,\n  \"defensive_override\": false,\n  \"order_result\": \"filled\",\n  \"actual_fill_price\": 138.155,\n  \"actual_slippage_bps\": 6.8,\n  \"budget_violation\": false\n}\n```\n\n---\n\n## Quick Decision Tree\n\n```\nTaker order needed — enforce slippage budget:\n│\n├── Is this a DEFENSIVE EXIT (cascade\u002Fkill-switch\u002Fstop breach)?\n│     └── YES → Submit market order. Log estimated slippage. Skip budget checks.\n│\n└── Normal taker execution path:\n      │\n      ├── 1. budget = per_order_slippage_budget_bps(expected_move)\n      │         └── budget == 0? → ABORT. Use Alo instead.\n      │\n      ├── 2. can_place, status = tracker.can_place_taker(estimated_slippage)\n      │         ├── can_place False? → ABORT. Session cap hit.\n      │         └── status \"warning\"? → Halve size. Continue.\n      │\n      ├── 3. sim = simulate_taker_fill(l2book, side, size, mid)\n      │         ├── sim.slippage > budget? → max_size_within_budget()\n      │         │         ├── adjusted > 0? → Use adjusted size.\n      │         │         └── adjusted == 0? → ABORT. Use Alo.\n      │         └── sim.feasible False? → Reduce to depth × 0.80. Re-simulate.\n      │\n      └── 4. Submit Ioc at worst_acceptable_price.\n               Post-fill: tracker.record_fill(). Log audit event.\n```\n",{"name":5,"category":36,"description":7},"main","cc32fdacf303e9c64064829787a5e690bb29cd47","multiclaw\u002Fmetaclaw\u002Fskills\u002Fexecution\u002Fslippage-budget-enforcement",0,"https:\u002F\u002Fgithub.com\u002Fenuno\u002Fhyperliquid-trading-firm","https:\u002F\u002Fgithub.com\u002Fenuno","https:\u002F\u002Fenuno.github.io\u002FDynamicCareerCanvas","Digital Nomad, Blockchain Evangel, and Digital Solutions Architect. \r\nCreator of TerraHash Stack.\r\nCEO of Ryno Crypto Mining Services.","2026-07-02 12:46:02",{"source":8,"skillName":5,"commands":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add enuno\u002Fhyperliquid-trading-firm --skill slippage-budget-enforcement",{"tool":63,"command":64},"bunx","bunx skills add enuno\u002Fhyperliquid-trading-firm --skill slippage-budget-enforcement",{"tool":66,"command":67},"pnpm","pnpm dlx skills add enuno\u002Fhyperliquid-trading-firm --skill slippage-budget-enforcement","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fenuno\u002Fhyperliquid-trading-firm\u002Fblob\u002Fmain\u002Fmulticlaw\u002Fmetaclaw\u002Fskills\u002Fexecution\u002Fslippage-budget-enforcement\u002FSKILL.md",true,[],[72,103,129,153,178,201],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":83,"publishedAt":43},"01M6J14V7SBT7MBPZ9VK8NRQR8","supermemory","Supermemory is a state-of-the-art memory and context infrastructure for AI agents. Use this skill when building applications that need persistent memory, user personalization, long-term context retention, or semantic search across knowledge bases. It provides Memory API for learned user context, User Profiles for static\u002Fdynamic facts, and RAG for semantic search. Perfect for chatbots, assistants, and knowledge-intensive applications.","https:\u002F\u002Fgithub.com\u002Fenuno\u002Fhyperliquid-trading-firm\u002Fblob\u002Fmain\u002Fskills\u002Fsupermemory\u002FSKILL.md",[78],{"categoryNo":79,"categoryName":80,"taxonomyType":81,"taxonomyTypeDesc":82},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",[74,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102],"ai agents","memory","rag","semantic search","infrastructure","search","user context","applications","api","knowledge","context","Art","personalization","across","learned","retention","profiles","for","persistent memory",{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":43},"01M6J14PEXHE2QBAWM3YZ2GM63","wolverine-strategy","WOLVERINE v2.0 — HYPE alpha hunter. Entry-only scanner, DSL-exit-only architecture. v1.1 lost -22.7% because the scanner's thesis exit chopped 25\u002F27 trades before DSL could manage them. v2.0 removes thesis exit entirely. Scanner decides entries (score 8+, 4H\u002F1H aligned, SM consensus). DSL manages all exits (wide Phase 1 for HYPE volatility, trailing tiers starting at +15% ROE). Leverage lowered to 7x. Max 4 entries\u002Fday. 3-hour cooldown between entries. DSL exit managed by plugin runtime via runtime.yaml.","MIT","https:\u002F\u002Fgithub.com\u002Fenuno\u002Fhyperliquid-trading-firm\u002Fblob\u002Fmain\u002Fskills\u002Fsenpi-skills\u002Fwolverine\u002FSKILL.md",[],[111,112,113,114,115,116,117,118,119,120,121,122,28,123,124,125,126,127,128,101],"strategy","wolverine strategy","architecture","alpha","Volatility","consensus","only","trading","scanner","manage","max","exit","entries","thesis","runtime","leverage","hunter","at",{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":138,"publishedAt":43},"01M6J14FQY9YG5QB45QK4D98AZ","wolf-strategy","WOLF v6.3 — Fully autonomous multi-strategy trading for Hyperliquid perps via Senpi MCP. Manages multiple strategies simultaneously, each with independent wallets, budgets, slots, and DSL configs. 5+N cron architecture: 5 shared wolf crons (Emerging Movers 3min, SM Flip 5min, Watchdog 5min, Risk Guardian 5min, Health Check 10min) plus one DSL v5.2 cron per strategy (native Hyperliquid SL sync via dsl-dynamic-stop-loss skill v5.3.1). Same asset can be traded in different strategies simultaneously. Enter early on first jumps, not at confirmed peaks. Dynamic risk-based leverage per strategy. Requires Senpi MCP connection, python3, mcporter CLI, OpenClaw cron system, and dsl-dynamic-stop-loss skill (provides dsl-cli.py + dsl-v5.py).","https:\u002F\u002Fgithub.com\u002Fenuno\u002Fhyperliquid-trading-firm\u002Fblob\u002Fmain\u002Fskills\u002Fsenpi-skills\u002Fwolf-strategy\u002FSKILL.md",[135],{"categoryNo":136,"categoryName":137,"taxonomyType":81,"taxonomyTypeDesc":82},"01JBSEEDCAT000000000000023","Skill与智能体开发",[111,139,140,141,142,143,113,144,145,118,28,146,147,148,126,149,150,151,128,152],"wolf strategy","MCP","openclaw","cli","sync","watchdog","autonomous","perps","strategies","shared","asset","native","wallets","hyperliquid perps",{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":160,"publishedAt":43},"01M6J14A20TMQ772M3H80XNB2T","wolf-howl","HOWL v2 — Hunt, Optimize, Win, Learn. Nightly self-improvement loop for the WOLF autonomous trading strategy. Runs once per day (via cron) to review all trades from the last 24 hours, compute win rates, analyze signal quality correlation, evaluate DSL tier performance, identify missed opportunities, and produce concrete improvement suggestions for the wolf-strategy skill. v2 adds fee drag ratio (FDR) analysis, holding period bucketing, LONG vs SHORT regime detection, rotation cost tracking, cumulative drift detection, and gross vs net profit factor separation. Use when setting up daily trade review automation, analyzing trading performance, or improving an autonomous trading strategy through data-driven feedback loops. Requires Senpi MCP connection, mcporter CLI, and OpenClaw cron system.","https:\u002F\u002Fgithub.com\u002Fenuno\u002Fhyperliquid-trading-firm\u002Fblob\u002Fmain\u002Fskills\u002Fsenpi-skills\u002Fwolf-howl\u002FSKILL.md",[159],{"categoryNo":136,"categoryName":137,"taxonomyType":81,"taxonomyTypeDesc":82},[161,140,162,142,163,164,165,166,167,168,145,169,170,171,172,173,174,175,176,177],"wolf howl","review","performance","learn","analysis","loop","analyze","short","up","optimize","drift","missed","self","factor","loops","profit","data-driven",{"skillNo":179,"name":180,"nameZh":6,"description":181,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":182,"licenseFileUrl":6,"sourceHtmlUrl":183,"categories":184,"keywords":185,"publishedAt":43},"01M6J1469QYZMD7E6JDP8Z9X1V","whale-index","Auto-mirror top Discovery traders on Hyperliquid. Scans top 50 traders, scores on PnL rank (35%), win rate (25%), consistency (20%), hold time (10%), drawdown (10%). Creates 2-5 mirror strategies with overlap checks. Daily rebalance with 2-day watch period before swaps. Use when setting up trader mirroring, copy trading, or portfolio auto-rebalancing based on Discovery leaderboard performance.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fenuno\u002Fhyperliquid-trading-firm\u002Fblob\u002Fmain\u002Fskills\u002Fsenpi-skills\u002Fwhale-index\u002FSKILL.md",[],[186,187,188,163,189,190,191,39,192,193,169,194,195,147,196,197,198,199,101,200],"index","whale","whale index","auth","monitoring","discovery","auto","portfolio","daily","time","with","consistency","top","mirror","pnl",{"skillNo":202,"name":203,"nameZh":6,"description":204,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":205,"categories":206,"keywords":207,"publishedAt":43},"01M6J141MJ2JMM7X3BGEEW30J9","vixen-strategy","VIXEN v1.0 — Dual-mode emerging movers scanner. Built from FOX v1.6 live trading data (+34.5% ROI). Two entry modes: STALKER (steady accumulation, score 6+, catches the SM buildup BEFORE the explosion) and STRIKER (violent FIRST_JUMP, score 9+, with raw volume confirmation to filter blow-off tops). 2-hour per-asset cooldown after Phase 1 exits. DSL High Water Mode mandatory.","https:\u002F\u002Fgithub.com\u002Fenuno\u002Fhyperliquid-trading-firm\u002Fblob\u002Fmain\u002Fskills\u002Fsenpi-skills\u002Fvixen\u002FSKILL.md",[],[111,208,209,210,211,212,118,119,28,213,214,215,149,196,216,217,218,219,220,221],"vixen strategy","roi","data","first","confirmation","volume","live","filter","explosion","mode","high","v1","modes","emerging movers"]