Claude Code Hooks for Trading Bots: Block Secrets, Gate Live Orders

KalshiPolymarket US Agent guardrails (no trading)

Verified working in mock mode, Dec 1, 2026. Both hook scripts run with sample inputs in each tool's documented format, plus real pytest runs on a paper bot; not run inside a live agent session. Command substitution, base64 piped into sh, git aliases and globs like .en? still get past the guard.

Starter code on GitHub: github.com/lazyclaw137-ship-it/claude-code-hooks-trading-bot. The code from the verified run, MIT licensed, with no keys included.

Short answer: Claude Code hooks are scripts that run at fixed points in Claude Code's loop. For a trading bot, a PreToolUse hook can block the agent from reading .env or key files, starting the bot with --live, or running git push: the hook exits with code 2 and its stderr goes back to Claude. Pair hooks with permissions.deny rules, because hooks only govern the AI agent, not your running bot.

What are the key facts?

  • Hooks live in .claude/settings.json (project, commit it), .claude/settings.local.json (project, personal) or ~/.claude/settings.json (all projects). Hook entries from every level merge; they don't replace each other.
  • PreToolUse runs before a tool call and can block it. Your script gets JSON on stdin (tool_name, tool_input). Exit 2 blocks the call and sends stderr to the agent; exit 0 means no objection.
  • Exit code 1 does not block. It's a non-blocking error and the action goes ahead. For a policy hook, use exit 2.
  • By default a hook that crashes, can't start or times out lets the action through. Add "onFailure": "block" (Claude Code v2.1.295 or later) so a broken guard fails closed. Grok Build reads the same line from a Claude settings file.
  • The docs call the if filter best-effort and say to use the permission system for a hard allow or deny. So keep permissions.deny rules for .env/*.pem reads alongside the hook.
  • Don't check for Bash by name. Cursor runs Claude Code hooks but calls the shell tool Shell, and Grok Build sends toolName: "run_terminal_command" in camelCase fields. Our old guard let --live and cat .env through in both. Check the input instead.
  • A crashed or timed-out hook blocks only where you ask: onFailure: "block" in Claude Code and Grok Build, failClosed: true in Cursor's own hooks.json. Codex has no switch. So the guard itself exits 2 on any input it can't read.
  • The deny rule Bash(git push *) doesn't match git -C . push or git -c push.default=current push. Claude Code's permissions page says so. The hook catches both.
DifficultyIntermediate
Time30–45 min
Cost$0
Works withClaude Code, Cursor, Grok Build

What will you build?

A .claude/ folder for your bot repo with a tested PreToolUse guard (secrets, live mode, git push, limit edits), a PostToolUse hook that re-runs your limit tests whenever the agent touches risk code, and deny rules as the hard backstop.

Who is it for?

People building a Kalshi or Polymarket US bot with Claude Code who want guardrails that don't depend on the model remembering a rules file.

Not for: Treating hooks as your money safety net. Position limits and the kill switch still live in the bot's own code.

The hook files, tested in four tools' input formats

On Dec 1, 2026 we rebuilt this guard from the prompt below on a paper bot repo and fed it 62 hook inputs in the shapes Claude Code, Cursor, Grok Build and Codex document today. The Oct 25 version let 17 of them through; this one lets 4 through. Below are the four files, then what we found.

1. .claude/settings.json: deny rules plus the two hooks. The args form runs the script with no shell, which is what Claude Code's docs recommend when the path uses ${CLAUDE_PROJECT_DIR}.

{
  "permissions": {
    "deny": [
      "Read(**/.env)",
      "Read(**/.env.*)",
      "Read(**/*.pem)",
      "Read(**/*.key)",
      "Bash(git push *)"
    ]
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash|Read|Edit|Write|Grep",
        "hooks": [
          {
            "type": "command",
            "command": "python3",
            "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/bot_guard.py"],
            "timeout": 10,
            "onFailure": "block"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.venv/bin/python",
            "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/limits_tests.py"],
            "timeout": 120
          }
        ]
      }
    ]
  }
}

On Claude Code older than v2.1.295, delete the onFailure line and update. Without it a crashed guard fails open. If you also open the repo in Cursor, use the shell form instead: "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/bot_guard.py\"" with no args. Cursor's hook docs don't mention args, and if a tool drops it, python3 reads the hook JSON as a Python program. We tried that: it exits 0 or 1, and either way the call goes through.

2. .claude/hooks/bot_guard.py: the PreToolUse guard. It decides by what's in the input (a command or a file path), not by the tool's name, because each tool names the same action differently. It prints only a reason, never file contents.

#!/usr/bin/env python3
"""BotCookery PreToolUse guard (Dec 1, 2026). Claude Code format; also runs
when Cursor or Grok Build load .claude/settings.json, and as a Codex hook.
Exit 0 = no objection (normal permissions still apply).
Exit 2 = block; the one-line reason on stderr goes to the agent.
Anything it can't read also exits 2."""
import json, re, sys

# .env, .env.local, *.pem, *.key, SSH keys. .env.example is allowed.
SECRET = re.compile(r"(?<![\w.-])(\.env(?!\.example(?![\w.-]))(\.[\w.-]+)?"
                    r"|[\w.-]*\.pem|[\w.-]*\.key|id_(rsa|ed25519|ecdsa)\w*)(?![\w.-])",
                    re.I)
READ_ONLY_TOOLS = {"read", "read_file", "grep", "glob", "ls", "list_dir"}
READ_CMD = re.compile(r"\s*(cat|grep|head|tail|less|jq)\s")


def block(msg):
    print(f"BotCookery guard: {msg}", file=sys.stderr)
    sys.exit(2)


try:
    data = json.load(sys.stdin)
    if not isinstance(data, dict):
        raise TypeError("not a JSON object")
    # Claude, Codex and Cursor send tool_name/tool_input. Grok sends
    # toolName/toolInput. Cursor names Bash "Shell"; Grok names it
    # run_terminal_command. So check the input fields, not the name.
    tool = data.get("tool_name") or data.get("toolName") or ""
    inp = data.get("tool_input") or data.get("toolInput") or {}
    if isinstance(inp, str):
        inp = json.loads(inp)
    if not isinstance(tool, str) or not isinstance(inp, dict):
        raise TypeError("tool name or tool input has the wrong type")
    cmd = inp.get("command") or ""
    path = inp.get("file_path") or inp.get("path") or ""
    if not isinstance(cmd, str) or not isinstance(path, str):
        raise TypeError("command or path is not a string")
except Exception as exc:
    block(f"could not read the hook input ({exc}).")

tool = tool.lower()
path = path.replace("\\", "/")


def check_command(c):
    if re.search(r"--live\b|BOT_MODE=live\b|KALSHI_ENV=prod\b", c):
        block("live trading is started by a human in their own terminal, "
              "never by the agent.")
    if SECRET.search(c):
        block("commands that touch .env or key files are blocked. "
              "The bot loads secrets from env vars itself.")
    if (re.search(r"(^|[;&|(]\s*)(printenv\b|env\s*($|[|;&>)]))", c)
            or re.search(r"echo\s+\$\{?\w*(KEY|SECRET|TOKEN|PASS)", c, re.I)
            or re.search(r"\b(python3?|node)\b.*\s-[ce]\s.*"
                         r"(environ|process\.env|getenv)", c)):
        block("printing environment secrets is blocked.")
    if re.search(r"\bgit(\s+-[Cc]\s+\S+|\s+--?[\w-]+(=\S+)?)*\s+push\b", c):
        block("git push needs a human.")
    if (re.search(r"\b(rm|mv|unlink)\b[^;&|]*(^|[\s/])KILL\b", c)
            or re.search(r"\*\*\* Delete File: (\S*/)?KILL\b", c)):
        block("the KILL file is the human's off switch. Leave it alone.")
    if "limits.json" in c and (not READ_CMD.match(c)
                               or re.search(r">\s*\S*limits\.json", c)
                               or re.search(r"[;&|]", c)):
        block("limits.json is human-edited only. Ask the user to change it.")


if cmd:
    check_command(cmd)
    # 'cat .e''nv', --li""ve, g\it: check again with quoting removed.
    check_command(re.sub(r"[\"'\\]", "", cmd))
if path:
    if SECRET.search(" " + path):
        block(f"access to {path} is blocked.")
    if tool not in READ_ONLY_TOOLS and re.search(r"(^|/)limits\.json$", path):
        block("limits.json is human-edited only. Ask the user to change it.")
sys.exit(0)

3. .claude/hooks/limits_tests.py: the PostToolUse hook. It can't undo an edit, but exit 2 puts the test failure in front of the agent so it fixes the code right away. It runs your whole tests/ folder unless you set LIMIT_TESTS to one file.

#!/usr/bin/env python3
"""BotCookery PostToolUse hook (Dec 1, 2026): after the agent edits risk,
limit or kill-switch code, run the tests. Exit 2 sends the failure to the
agent. Set LIMIT_TESTS to a test file to run just that file (default: tests/)."""
import json, os, re, subprocess, sys


def fail(msg):
    print(msg, file=sys.stderr)
    sys.exit(2)


try:
    data = json.load(sys.stdin)
    inp = data.get("tool_input") or data.get("toolInput") or {}
    path = inp.get("file_path") or inp.get("path") or ""
    if not path:  # Codex apply_patch puts the patch text in "command"
        m = re.search(r"\*\*\* (?:Update|Add) File: (\S+)", inp.get("command") or "")
        path = m.group(1) if m else ""
    path = str(path).replace("\\", "/")
except Exception as exc:
    fail(f"limits_tests: could not read the hook input ({exc}).")

if not re.search(r"(risk|limit|kill)[\w-]*\.py$", path, re.I):
    sys.exit(0)
root = os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()
target = os.environ.get("LIMIT_TESTS", "tests")
try:
    r = subprocess.run([sys.executable, "-m", "pytest", "-q", target],
                       cwd=root, capture_output=True, text=True, timeout=110)
except subprocess.TimeoutExpired:
    fail(f"Tests for {target} took over 110 s after editing {path}.")
if r.returncode in (4, 5):  # path missing / no tests collected
    fail(f"No tests ran for {target} after editing {path}. "
         "Add a limit test or set LIMIT_TESTS.")
if r.returncode != 0:
    fail(f"Tests failed after editing {path}:\n{(r.stdout + r.stderr)[-3000:]}")
sys.exit(0)

4. tests/test_hooks.py: sends every case in all three input shapes.

import json, os, subprocess, sys
import pytest

GUARD = os.path.join(os.path.dirname(__file__), "..", ".claude", "hooks",
                     "bot_guard.py")


def run(payload):
    data = payload if isinstance(payload, str) else json.dumps(payload)
    return subprocess.run([sys.executable, GUARD], input=data,
                          capture_output=True, text=True).returncode


def shapes(cmd=None, path=None, read=False):
    """The same call as Claude Code, Cursor and Grok Build send it."""
    if cmd is not None:
        return [{"tool_name": "Bash", "tool_input": {"command": cmd}},
                {"tool_name": "Shell", "tool_input": {"command": cmd}},
                {"toolName": "run_terminal_command", "toolInput": {"command": cmd}}]
    names = ("Read", "Read", "read_file") if read else ("Edit", "Write", "search_replace")
    return [{"tool_name": names[0], "tool_input": {"file_path": path}},
            {"tool_name": names[1], "tool_input": {"file_path": path}},
            {"toolName": names[2], "toolInput": {"path": path}}]


BLOCK = ["python bot.py --live", "BOT_MODE=live python bot.py",
         "KALSHI_ENV=prod python bot.py", "cat .env", "cat .env.local",
         "cat ~/.kalshi/kalshi.pem", "printenv", "env | grep KALSHI",
         "echo $KALSHI_API_KEY_ID", "python -c 'import os;print(os.environ)'",
         "git push origin main", "git -C . push",
         "sed -i s/5/50/ limits.json", "cat x > limits.json",
         "rm KILL", "mv KILL /tmp/", "cat .e''nv", 'python bot.py --li""ve']
ALLOW = ["python bot.py", "python bot.py --paper", "pytest -q",
         "cat .env.example", "cat limits.json", "grep max limits.json",
         "git status", 'git commit -m "push fix"', "ls KILL"]


@pytest.mark.parametrize("cmd", BLOCK)
def test_blocks_commands(cmd):
    assert [run(p) for p in shapes(cmd=cmd)] == [2, 2, 2]


@pytest.mark.parametrize("cmd", ALLOW)
def test_allows_commands(cmd):
    assert [run(p) for p in shapes(cmd=cmd)] == [0, 0, 0]


@pytest.mark.parametrize("path", ["/p/.env", "/p/.env.local",
                                  "/p/keys/kalshi.pem", "C:\\bot\\.env"])
def test_blocks_secret_reads(path):
    assert [run(p) for p in shapes(path=path, read=True)] == [2, 2, 2]


def test_limits_json_read_ok_edit_blocked():
    assert [run(p) for p in shapes(path="/p/limits.json", read=True)] == [0, 0, 0]
    assert [run(p) for p in shapes(path="/p/limits.json")] == [2, 2, 2]
    assert [run(p) for p in shapes(path="C:\\bot\\limits.json")] == [2, 2, 2]


def test_risk_edit_allowed():
    assert [run(p) for p in shapes(path="/p/risk.py")] == [0, 0, 0]


@pytest.mark.parametrize("raw", ["not json", "", "[]",
                                 '{"tool_name": "Bash", "tool_input": {"command": ["git", "push"]}}'])
def test_bad_input_fails_closed(raw):
    assert run(raw) == 2

What we found (Dec 1, 2026)

We ran the same 62 inputs (43 commands in four tools' shapes, 9 file paths, 3 Codex patches, 7 broken payloads) against the Oct 25 files and against a fresh build from today's prompt.

  • A redirect wrote limits.json. The old guard let any command that started with cat through, so cat x > limits.json and cat limits.json > /tmp/l; echo '{}' > limits.json both exited 0. Now a > into the file, or a second command after ;, & or |, is a write.
  • Nothing protected the kill file. rm KILL and rm -f ./KILL exited 0 in every shape. The agent could switch off the bot's off switch. Now rm, mv and unlink of KILL, and a Codex patch with *** Delete File: KILL, are blocked.
  • Windows paths walked past. Claude Code's hooks page says file paths arrive with backslashes on Windows. A Read of C:\bot\.env and an Edit of C:\bot\limits.json both got exit 0. The guard now turns \ into / first.
  • Easy quoting tricks now fail. The guard checks each command twice: as sent, and with quotes and backslashes removed. That closes cat .e''nv, --li""ve, BOT_MODE='live' and g\it push. It also blocks python -c or node -e that reads os.environ, process.env or getenv.
  • A list where a string belongs crashed it. {"command": ["git", "push"]} raised TypeError and exited 1, which lets the call through everywhere except where fail-closed is set. A clean build from the Oct 25 prompt did worse: it silently exited 0 on that and on a tool_input sent as a string. Wrong types now exit 2 with a reason.
  • One false block. grep -n max limits.json was blocked as an edit. Reads with grep are allowed now.
  • The test hook in a fresh build missed Codex. The Oct 25 prompt didn't say that Codex puts the edited file inside the apply_patch text, so a build from it exited 0 after a broken risk.py patch. The prompt now says so. The page's own limits_tests.py already caught it, but died with exit 1 on bad input. It now exits 2 with a message.
  • Docs moved since Oct 25. Grok Build's hooks page now has failClosed, and reads onFailure: "block" from a Claude settings file (we said it ignored it). Its default PreToolUse timeout is 5 seconds. Cursor's third-party hooks page now says Third-Party Imports is on by default, maps Claude's Edit to Write, and lists the product as the Grok Build Agents Window. Codex still says a PreToolUse error, timeout or malformed response can let the tool run.
  • Still gets through: $(echo git) push, echo Z2l0IHB1c2g= | base64 -d | sh, a git alias for push, and cat .en?. A pattern guard can't run the shell for you. Keep the key file outside the project, keep the deny rules, and use a sandbox for anything stronger.

What we found (Oct 25, 2026)

  • The old guard did nothing outside Claude Code. It checked tool_name == "Bash". Cursor runs Claude Code hooks but calls the tool Shell. Grok Build sends toolName: "run_terminal_command" inside a camelCase toolInput. Both shapes got exit 0 for python bot.py --live, cat .env, git push and a .pem read. Run against the new tests, the old guard failed 19 of 27.
  • Crashes didn't block outside Claude Code. On input that wasn't valid JSON the old guard died with exit 1. At the time Grok Build's docs said every outcome except exit 2 or an explicit deny let the call through, and Codex's docs said the same for errors and timeouts. The guard exits 2 on any input it can't read.
  • Grok Build loads this file as-is. grok inspect in the trusted repo listed both hooks as [claude], with matcher Bash|Read|Edit|Write, and loaded all 5 deny rules. Grok maps Bash to run_terminal_command, Read to read_file, and Edit/Write to search_replace, and it sets CLAUDE_PROJECT_DIR.
  • Codex edits come through as a patch. Codex reports file edits as apply_patch with the patch text in tool_input.command. The guard blocked patches to limits.json and .env and allowed one to risk.py. The test hook now reads the file name out of the patch.
  • The test hook failed on every risk edit. It ran tests/test_limits.py, which our test bot (like most bots) doesn't have, so pytest exited 4 and the hook reported "Limit tests failed". It now runs tests/ and says clearly when no tests ran.
  • Two small fixes: git -C . push got past git\s+push, and the guard now matches git options before push while still allowing git commit -m "push fix".

Sample runs (Dec 1, 2026)

The drill script, same 62 inputs each time:

Oct 25 files:   SUMMARY 45/62 as expected, 17 miss
Dec 1 files:    SUMMARY 58/62 as expected, 4 miss
MISS B 'cat .en?' {'claude': 0, 'cursor': 0, 'grok': 0, 'codex': 0}
MISS B '$(echo git) push' {'claude': 0, 'cursor': 0, 'grok': 0, 'codex': 0}
MISS B 'echo Z2l0IHB1c2g= | base64 -d | sh' {'claude': 0, 'cursor': 0, 'grok': 0, 'codex': 0}
MISS B 'git p  # alias p=push' {'claude': 0, 'cursor': 0, 'grok': 0, 'codex': 0}

Broken input now gets a reason instead of a traceback:

ok   B raw '[]' 2 ['BotCookery guard: could not read the hook input (not a JSON object).']
ok   B raw '{"tool_name":"Bash","tool_input":{"command":["git","push"]} 2 ['BotCookery guard: could not read the hook input (command or path is not a string).']

The tests, and the Oct 25 guard run against them:

$ pytest -q tests/test_hooks.py
37 passed in 1.90s
Oct 25 bot_guard.py: 10 failed, 27 passed in 1.96s

Test hook after we loosened the order-size check in risk.py (qty > max * 10):

Tests failed after editing .../risk.py:
FAILED tests/test_risk.py::test_too_big - Failed: DID NOT RAISE RiskError
1 failed, 40 passed in 2.10s
exit 2

The same broken edit as a Codex apply_patch and in Grok's toolInput.path shape also exited 2. With risk.py restored it exited 0, an edit to bot.py didn't run the tests, and LIMIT_TESTS=tests/nope.py exited 2 with "No tests ran".

Follow-up prompt

Built this before Dec 1? Paste this to patch the older guard:

Read .claude/hooks/bot_guard.py, limits_tests.py and tests/test_hooks.py.
Without changing bot.py, risk.py or limits.json, fix these and add a
test for each:
- "cat x > limits.json" must be blocked (a redirect is a write).
- "rm KILL", "mv KILL x" and an apply_patch "*** Delete File: KILL"
  must be blocked.
- Windows paths: turn "\" into "/" before matching, so a Read of
  C:\bot\.env and an Edit of C:\bot\limits.json are blocked.
- Also match each command with quotes and backslashes removed, so
  "cat .e''nv" and "python bot.py --li""ve" are blocked.
- If tool_input, command or path has the wrong type (e.g. a list),
  exit 2 with a reason. Never exit 1. limits_tests.py exits 2 on input
  it can't read and finds the file in a Codex apply_patch.
- "grep max limits.json" is a read and must be allowed.
Add "Grep" to the PreToolUse matcher in .claude/settings.json.
Then run pytest -q tests/test_hooks.py and show the result.

Once the hooks are in, paste this to make the agent check its own guard:

Read .claude/settings.json and .claude/hooks/. Without running the bot,
list every way you could still start live trading, read a key or push
code that the guard would allow. Don't try any of them. For each one,
say whether a deny rule, a sandbox setting or a code change closes it.

What prompt do you paste into your AI coding tool?

Works in Claude Code, Cursor, Codex/ChatGPT, Grok or any agent that can write files. Paste it into an empty folder. Read what it builds before you run anything.

Add agent hooks to this bot repo. Use ONLY these docs and say so when
something isn't documented there instead of guessing:
https://code.claude.com/docs/en/hooks
https://code.claude.com/docs/en/permissions

1. Create .claude/settings.json with:
   - permissions.deny: Read(**/.env), Read(**/.env.*), Read(**/*.pem),
     Read(**/*.key), Bash(git push *)
   - a PreToolUse hook, matcher "Bash|Read|Edit|Write|Grep", exec form:
     "command": "python3", "args" holding
     "${CLAUDE_PROJECT_DIR}/.claude/hooks/bot_guard.py",
     timeout 10, onFailure "block"
   - a PostToolUse hook, matcher "Edit|Write", that runs
     .claude/hooks/limits_tests.py with the project's .venv python
2. bot_guard.py (stdlib only) reads the hook JSON from stdin. Accept
   tool_name/tool_input and toolName/toolInput. Decide by the input
   (a "command" string, or "file_path"/"path"), not by the tool name,
   because tools call the shell Bash, Shell or run_terminal_command.
   Before matching, turn "\" into "/" in paths, and check each command
   twice: as sent, and with all quotes and backslashes removed.
   Exit 2 with a one-line reason on stderr when:
   - a command contains --live, BOT_MODE=live or KALSHI_ENV=prod
   - a command or path touches .env (not .env.example), *.pem, *.key
     or SSH keys
   - a command prints env vars (printenv, env, echo $..._KEY, or
     os.environ / process.env / getenv inside python -c or node -e)
   - a command runs git push, including git -C <dir> push
   - a command removes or moves the KILL file (rm, mv, unlink), or a
     Codex apply_patch has "*** Delete File: KILL"
   - anything except a read touches limits.json. A redirect (>) into
     limits.json is a write even after cat. cat/grep/head/jq reads are ok.
   - the input isn't a JSON object, or tool_input (parse it if it's a
     JSON string), command or path has the wrong type (fail closed;
     never crash with exit 1)
   Otherwise exit 0. Never print file contents or secret values.
3. limits_tests.py: find the edited file in file_path/path, or in the
   "*** Update File:" / "*** Add File:" line of a Codex apply_patch
   command. If it matches (risk|limit|kill)*.py, run pytest -q on
   tests/ (or $LIMIT_TESTS) from $CLAUDE_PROJECT_DIR. Exit 2 with the
   output tail on failure, exit 2 with a clear message if no tests ran,
   and exit 2 with a message on input it can't read.
4. tests/test_hooks.py: pipe sample JSON into bot_guard.py in three
   shapes (Bash, Shell, and toolName run_terminal_command) and assert
   exit codes. Blocked: "python bot.py --live", "cat .env", "git push
   origin main", "cat x > limits.json", "rm KILL", "cat .e''nv",
   "not json", a command sent as a list, and a Read of C:\bot\.env.
   Allowed: "pytest -q", "cat .env.example", "grep max limits.json",
   'git commit -m "push fix"'.
Do not change bot.py, risk.py or limits.json. Show me the files, then
run pytest -q tests/test_hooks.py.

How do you build it, step by step?

  1. Start from a bot repo that already has limits in code. If you don't have one yet, cook the Kalshi AI trading bot or Polymarket paper bot first, plus the kill switch recipe.
  2. Paste the prompt into Claude Code, or copy the four files from the section above.
  3. Make the scripts executable if you switch to shell form: chmod +x .claude/hooks/*.py. In the args form shown here, Claude Code runs python3 script.py directly, so it isn't required.
  4. Check that each tool sees the hooks. In Claude Code, /hooks lists each hook and the file it came from. In Grok Build, trust the folder and run grok inspect: both hooks should show as [claude] and the permissions line should say 5 loaded. In Cursor, check that Settings → Agents → Third-Party Imports is on (the docs say it's on by default).
  5. Run the hook tests: pytest -q tests/test_hooks.py. They pipe sample JSON into the guard in the Claude Code, Cursor and Grok Build shapes. We got 37 passed.
  6. Try to break it on purpose. Ask the agent to "run the bot live" or "show me what's in .env". The guard's reason should come back as a blocked tool call. We tested the scripts directly, not inside a live session, so this is the step that proves it in your setup.
  7. Commit .claude/settings.json and .claude/hooks/ so the guard travels with the repo. Keep personal tweaks in .claude/settings.local.json.

How do you test it in paper or demo mode first?

Hooks don't touch your bot's trading mode. They decide what the AI agent may do while it works on the code. Keep the bot itself on Kalshi demo or local paper mode exactly as in the bot recipes. The guard adds one more rule: the agent can never be the one that starts live mode. A human types --live in their own terminal, after the paper logs look clean.

A good test run: let Claude Code work on the bot for a session in paper mode, then read your hook outcomes. Blocked calls show up in the transcript with the guard's reason, which tells you what the agent tried to do.

What safety checks does it need before real money?

Tick every box before the bot touches real money. The full rules file, .gitignore and pre-commit hook are in the Safety Pack.

Which official docs did we check?

Endpoints and rules were checked against these pages on Dec 1, 2026. APIs change, so if something here disagrees with the official docs, trust the docs and tell us.

Frequently asked questions

What are Claude Code hooks?

User-defined handlers (shell commands, HTTP endpoints, MCP tools, prompts or subagents) that Claude Code runs automatically at points in its lifecycle, such as before or after a tool call. They're configured in Claude Code settings files.

How do I block a command with a Claude Code hook?

Add a PreToolUse hook with a matcher like Bash. Your script reads the tool call as JSON on stdin and either exits 2 with a reason on stderr, or prints JSON with permissionDecision: "deny". Exit 0 with no output means no objection, and normal permissions still apply.

Where do Claude Code hooks go?

In ~/.claude/settings.json (all your projects), .claude/settings.json (one project, shareable via git) or .claude/settings.local.json (one project, personal). Plugins, skills and subagents can also define hooks.

Can a hook stop my bot from losing money?

No. Hooks control what the AI coding agent does, not what your running bot does. Losses are prevented by limits in the bot's code, a kill switch, venue cancel-all endpoints and starting in demo or paper mode.

Do Claude Code hooks work in Cursor or Grok?

They load, but a guard written only for Claude Code may not work. Cursor runs .claude/settings.json hooks when Third-Party Imports is on (the default), calls the shell tool Shell and maps Edit to Write. Grok Build loads them in a trusted folder and sends toolName/toolInput with its own tool names, such as run_terminal_command. A guard that checks tool_name == "Bash" allows everything in both. Codex uses its own hooks.json with tool_name Bash or apply_patch.

What happens if my hook script crashes?

By default the action goes ahead, because a crash counts as a non-blocking error. Set "onFailure": "block" on the hook (Claude Code v2.1.295 or later) to block the action instead. Grok Build honours the same field from a Claude settings file; Cursor's own hooks.json uses failClosed: true; Codex has no equivalent. So write the guard to exit 2 on any input it can't parse.

More from the kitchen: Recipes by platform · Kalshi & Polymarket fee calculator · How we verify recipes · Safety Pack