Episode 10 · AI Trading · Building a Complete Trading System

Ten rules and a five-step loop for working with an agent

Explore, plan, build, check and commit, then an independent review: run the full loop on a round-down lot function with five tests, and read the diff yourself.

An agent reads files, runs commands and edits code. It works fast, it doesn’t know tomorrow’s price, and it can be wrong while sounding certain. AI can’t predict the future or sudden market moves, and a promise of unusually high returns from an “AI bot” is a classic sign of fraud.

This post gives you ten rules for every session, a five-step loop for every job you hand an agent, and a full run of that loop on a small, real function.

Three terms used below:

  • Hallucination: the AI invents a number or a source and states it as fact.
  • Look-ahead: code uses data that didn’t exist at the moment of the decision.
  • Repaint: a signal redraws itself after the candle closes.

Ten rules for every session

The safety floor under all ten: anything that can place an order uses a demo account only; an API key, if you have one, never has withdrawal rights; never paste a key or password into the chat; a human approves before any order.

# Rule Why
1 AI is a work assistant, not a signal source. It doesn’t know the future.
2 Always state the data timestamp in the prompt, e.g. “data up to 2026-11-11 01:00 UTC”. Blocks look-ahead and invented “current” figures.
3 Current prices and numbers come from you (copied from your platform) or from a data connection with a known origin. The model has no live data unless it’s connected.
4 Make the AI cite where a number came from; no origin means unverified. Anti-hallucination techniques reduce errors, they don’t remove them.
5 Allow, and require, “not enough data”. Fewer confident wrong answers.
6 Spec first, code second; approve the plan before the agent edits files. Without what only you know (units, rounding), it builds something else; fixing a plan is cheaper than unpicking code.
7 Write the risk rules once in the project instructions file (AGENTS.md); block the absolute no-gos in configuration (deny rules, hooks). Doesn’t depend on each session’s memory. Instructions are guidance the agent may decide don’t apply; only deny rules and hooks block.
8 Trading code runs in backtest and demo first; while learning, never give the agent order rights on a live account. A software bug plus missing guardrails loses money very fast.
9 Review look-ahead and repaint with an independent agent or read-only subagent. Authors rarely see their own bugs; a fresh reviewer isn’t carried along by the original reasoning.
10 Recompute lot and risk yourself; round down to the 0.01 step; if it doesn’t reach one step, no trade. Lot is deterministic (same input, same output): give it to tested code, not to “judgement”.

Rule 8 has a famous case. On 1 August 2012, Knight Capital’s faulty order router sent more than 4 million orders in the first 45 minutes of trading, while it only needed to fill 212 customer orders. The firm lost more than 460 million USD. An internal system had sent 97 automated error emails before the open, and nobody acted on them. The regulator’s 12 million USD fine in October 2013 pointed specifically at missing deployment and testing procedures.

The five-step loop

Explore → Plan → Build → Check and commit → Independent review. Each step ends at a gate where you approve. Each loop does one small thing (a function, an indicator); a big job becomes several loops, one commit each.

The loop pulls together a handful of habits:

  • Use Plan mode for changes you want to see first: the agent reads and proposes, and edits nothing until you approve the plan.
  • Give the agent a check that returns pass or fail, such as a test file.
  • Ask for evidence: the command it ran and the output. “All tests pass” on its own says very little.
  • Have someone who didn’t watch the code being written review it.
  • Make a Git checkpoint (a commit) before and after each job.
  • Never delete or edit tests; never hard-code a value just to make a test pass; never guess about code that hasn’t been opened.
Step Mode Your job What to type
1. Explore Plan Let the agent read the folder, data and old code. Read its summary and point out what it got wrong. “Read the folder and summarize the files and data. Change nothing. Ask me about anything unclear.”
2. Plan Plan (gate) Approve the spec and plan: files to change, assumptions, risks, tests. “Write a step-by-step plan: files to create or edit, assumptions, risks and tests. Wait for my approval.”
3. Build Manual Read every prompt before approving. Press Esc if the agent drifts. “Follow the approved plan. Write the tests first. Don’t delete tests or change their expectations.”
4. Check and commit You Run the tests yourself, read the diff, work one case by hand, then commit. “List the files changed, the test command you ran and its output verbatim.”
5. Independent review Read-only subagent or a new session A reviewer who didn’t see the writing; real bugs go into a new loop. /code-review HEAD~1..HEAD, or “Use a read-only subagent to review the last commit against the spec; report only correctness bugs.”

Three controls to know while the agent is running (Claude Code):

  • Esc stops at once and keeps what’s done.
  • /rewind, or Esc twice on an empty input, takes the code, the conversation or both back to an earlier point.
  • /clear starts a clean conversation. If you’ve corrected the same mistake twice and it’s still wrong, /clear and write one new prompt that includes what you learned, instead of a third correction.

Claude Code’s restore points only track files it changed with its own edit tool, not files changed by shell commands. They go alongside Git; they don’t replace it.

Pick the permission mode for each step

Claude Code has four main modes:

  • Plan: reads files, may run commands to investigate and writes a plan, but doesn’t edit source until you approve.
  • Manual: asks before most file edits, commands and network access.
  • Accept edits: accepts file edits and basic file commands in the project folder on its own, including rm.
  • Auto: a classifier looks at each action and blocks risky ones. It reduces prompts; it doesn’t guarantee safety.

While learning: Explore and Plan in Plan mode, Build in Manual, no Auto. From version 2.1.283, new Claude Code sessions in the terminal and VS Code open in Auto when it’s available, on every plan, so always look at the mode before your first message.

  1. Open a terminal in the project folder (cd C:\trading-agent-lab, or cd ~/trading-agent-lab on macOS).
  2. Run claude --permission-mode plan. The status bar must show ⏸ plan mode on. Inside a session, Shift+Tab cycles the modes (auto → manual → accept edits → plan); on Windows, if Shift+Tab doesn’t switch, use Alt+M. If the bar shows ⏵⏵ auto mode on, keep pressing.
  3. When the plan is ready, Claude asks how to continue. Choose “Yes, manually approve edits”. Not “Yes, and use auto mode”, and not “Yes, auto-accept edits”. To change the plan choose “No, keep planning” and type your notes; Ctrl+G opens the plan in an editor.
  4. In Manual, each prompt names the file or command. Read it, then choose Yes. Avoid “Yes, and don’t ask again” for commands that touch the network, delete files or send data: it’s saved as a lasting allow rule in .claude/settings.local.json. While a prompt is open, don’t press Shift+Tab: there it selects “allow for the whole session”.

In the desktop app’s Code tab, the mode picker sits under the input box. Your choice is remembered per folder, except Plan, which applies only to the current session. After approving the plan, check that the picker is on Manual before the agent edits; Manual shows a diff with approve and reject buttons for each change.

Manual has a downside: after about ten prompts, people start approving without reading. The cure is small jobs, so there are few prompts and you read each one.

“Auto” means different things in different tools. Codex Auto edits inside the folder and asks when it goes outside; Claude Auto is the self-approving classifier.

Never enable the skip-all-permissions modes: bypassPermissions (Claude Code), Skip (Cowork), --yolo (Codex), Allow all (VS Code). They don’t protect against prompt injection (content the agent reads that contains instructions to it) or unintended actions, and are meant for isolated containers or VMs.

Tool Steps 1–2 (Explore, Plan) Step 3 (Build) Don’t use while learning
Claude Code (terminal) claude --permission-mode plan, or Shift+Tab until ⏸ plan mode on Approve the plan with “Yes, manually approve edits” Auto, including “Yes, and use auto mode”; --dangerously-skip-permissions
Claude desktop, Code tab Plan in the mode picker Manual: review the diff, approve or reject each change Auto; Bypass permissions; Accept edits unless you read every diff
Claude Cowork Manual (Auto is the default on paid plans); read the plan first Manual Skip
Codex codex --sandbox read-only --ask-for-approval on-request The Auto preset (plain codex in a Git folder): edits and runs in the folder, asks outside it or for network; /permissions shows and changes it --dangerously-bypass-approvals-and-sandbox (--yolo)
VS Code + Copilot Plan in the agent list, or /plan Keep Manual permissions (default); review the diff before committing Allow all; Autopilot; /yolo or /autoApprove; chat.tools.global.autoApprove

Optional: make terminal sessions open in Plan. In .claude/settings.json, change defaultMode from "default" to "plan" and keep every deny rule and any env block. JSON is strict: no comments, no trailing commas. Start a new session and run /status; Setting sources must include the project settings. This line only applies to terminal sessions in the project folder: the VS Code extension doesn’t read it from the project file, the desktop app prefers its picker, and auto or bypassPermissions set in a project file have no effect.

{
  "permissions": {
    "defaultMode": "plan",
    "deny": [
      "Read(./.env)",
      "Read(./.env.*)",
      "Edit(./config/thresholds.json)",
      "Edit(./AGENTS.md)",
      "Edit(./CLAUDE.md)"
    ]
  }
}

For Codex with an MCP server, default_tools_approval_mode = "writes" asks before any tool not marked read-only.

The full loop: a lot function with five tests

A small function you’ll reuse: lot size from risk, rounded down to the 0.01 step; below one step it returns 0, meaning no trade. Tests run with pytest.

Before you start, once:

  1. git status must say nothing to commit, working tree clean. If not, git add -A and git commit -m "Checkpoint before lot function".
  2. Install pytest into the project’s .venv:
cd C:\trading-agent-lab
.venv\Scripts\python -m pip install -U pytest
.venv\Scripts\python -m pytest --version

On macOS use .venv/bin/python. Expect Successfully installed ... pytest (or Requirement already satisfied) and then pytest 9.x. not recognized means there’s no .venv yet or you’re in the wrong folder.

The five check cases to paste into the prompt:

Case Input Working Lot
XAUUSD, balance 1,000 USD Risk 10 USD, SL 6 USD, 100 USD per 1 USD of price per lot 10 ÷ 600 = 0.0166 0.01
XAUUSD, balance 2,000 USD Risk 20 USD, SL 7.5 USD, 100 20 ÷ 750 = 0.0266 0.02
EURUSD Risk 20 USD, SL 30 pips, 10 USD per pip per lot 20 ÷ 300 = 0.0666 0.06
BTCUSD CFD Risk 20 USD, SL 900 USD, 1 USD per 1 USD of price per lot 20 ÷ 900 = 0.0222 0.02
XAUUSD, balance 500 USD Risk 5 USD, SL 6 USD, 100 5 ÷ 600 = 0.0083 0: no trade

Steps 1–2 (Plan). Paste part A of the prompt at the end of this post with the table. The plan passes when it names five things: the two files to create; tests first, then the function; the five cases with expected results; the test command using the .venv Python; a promise not to edit tests. If anything is missing, choose “No, keep planning” and say what.

Step 3 (Manual). Choose “Yes, manually approve edits”. The agent creates tests/test_lot.py first; compare the five assert lines with the table. It then asks to run pytest, and this time it must fail, usually with ModuleNotFoundError: No module named 'src.lot'. That failure is the point: it proves the tests check something that doesn’t exist yet. Then it creates src/lot.py. The wording may differ from the reference below, but it must round down with math.floor, return 0 below one step and raise an error when risk or stop distance isn’t positive.

src/lot.py (reference):

import math

def lot_round_down(risk_usd, sl_distance, value_per_unit_per_lot, step=0.01):
    '''Lot rounded DOWN to the step; returns 0.0 below one step (no trade).

    value_per_unit_per_lot: USD lost by 1 lot when price moves 1 unit of sl_distance against you.
    Conventions: XAUUSD 100 (SL in USD), EURUSD 10 (SL in pips), BTCUSD CFD 1 (SL in USD).
    '''
    if risk_usd <= 0 or sl_distance <= 0:
        raise ValueError('risk and SL distance must be positive')
    raw = risk_usd / (sl_distance * value_per_unit_per_lot)
    steps = math.floor(raw / step + 1e-9)   # +1e-9: floating-point tolerance
    return round(steps * step, 8)

tests/test_lot.py:

from src.lot import lot_round_down as lot

def test_xau_balance_1000_sl_6():
    assert lot(10, 6, 100) == 0.01      # 10 / 600 = 0.0166 -> 0.01

def test_xau_balance_2000_sl_7_5():
    assert lot(20, 7.5, 100) == 0.02    # 20 / 750 = 0.0266 -> 0.02

def test_eurusd_sl_30_pips():
    assert lot(20, 30, 10) == 0.06      # 20 / 300 = 0.0666 -> 0.06

def test_btc_cfd_sl_900():
    assert lot(20, 900, 1) == 0.02      # 20 / 900 = 0.0222 -> 0.02

def test_below_one_step_is_no_trade():
    assert lot(5, 6, 100) == 0.0        # 5 / 600 = 0.0083 -> 0: no trade

Check one case by hand: 20 ÷ (7.5 × 100) = 0.0266; divided by the 0.01 step that’s 2.66, rounded down to 2 steps, so 0.02 lot. Real risk is 0.02 × 7.5 × 100 = 15 USD, under the 20 USD allowed.

The +1e-9 is a floating-point tolerance, not rounding up. Computers store most decimals approximately, the way 1 ÷ 3 written out is only 0.333…, so 0.29 ÷ 0.01 is stored as 28.999…; without the tolerance an exact 0.29 lot would come out as 0.28.

These cases are worked examples, not investment advice.

Check before you believe “done”

“Done, all tests pass” isn’t evidence. An agent stops when the job looks done, and without a check to run, “looks done” is all it has. Evidence is four things: the list of changed files, test output you ran yourself, a hand calculation that matches, and a commit with a clear message.

Do step 4 in a second terminal in the same folder (in the desktop app, Ctrl+` opens one next to the session). Type one line at a time and read the result before the next.

cd C:\trading-agent-lab
git status
git add -A
git diff --staged --stat
git diff --staged
.venv\Scripts\python -m pytest -q tests\test_lot.py
.venv\Scripts\python -m pytest -q

Why git add -A first? New files are untracked, and plain git diff doesn’t show them. After adding, git diff --staged shows everything.

Read the diff with four questions:

  1. Did any file change outside the plan?
  2. Was any test deleted, or its expectation changed?
  3. Is there a value hard-coded just to pass a test?
  4. Did a network call, a secret-file read or an order function appear?

One “yes” means stop: don’t commit, go back to step 2. A suspicious diff looks like this, passing the test without computing anything:

+    if risk_usd == 20 and sl_distance == 7.5:
+        return 0.02
Command What you see Stop if
git status Branch name; edited files as modified; new files under Untracked files A file outside the plan; .env, .venv/ or __pycache__/ (missing .gitignore)
git add -A Usually nothing; on Windows maybe an LF/CRLF warning, harmless A path or permission error
git diff --staged --stat One line per file with lines added (+) and removed (-) A file outside the plan; lines removed from tests/
git diff --staged Each change: + added, - removed. If it pauses at :, Space scrolls, q quits Changed test expectations; hard-coded values; new network, .env or order code
pytest -q tests\test_lot.py Five dots, then 5 passed in 0.05s failed or error; a count other than 5
pytest -q (whole project) Everything passes; the count may be higher than 5 failed or error: the change broke something older

Only when all of that is right:

git commit -m "Add round-down lot function and 5 tests"
git log --oneline

To undo an add without committing, git restore --staged . (with the final dot) unstages everything and keeps file contents. To put back one file from the last commit, for example an edited test, git restore --staged --worktree tests/test_lot.py touches only that file. Don’t run the dotted form git restore --staged --worktree . unless you understand it: it also wipes new files you added.

Error Fix
fatal: not a git repository The terminal isn’t in the project folder: cd again
git diff shows nothing although files were created They’re untracked: git add -A, then git diff --staged
No module named pytest pytest isn’t in .venv: run the install command
ModuleNotFoundError: No module named 'src' Run from the project root with python -m pytest, which adds the current folder to the module path
no tests ran File and function names must start with test_
1 failed, 4 passed Read the FAILED line; fix the function to the spec, not the test
nothing to commit, working tree clean The agent didn’t write anything, or you’re in another folder

Step 5. /code-review (Claude Code), /review (Codex) or a read-only subagent with part B of the prompt. Real bugs it finds go into a new loop.

The autonomy ladder: write the conditions first

Four levels:

  • Level 0: question and answer.
  • Level 1: the agent reads and writes in the project folder; it never touches a trading account.
  • Level 2: the agent proposes orders in a fixed template, code checks the limits, you approve and place them on demo.
  • Level 3: automated on demo with hard limits and a kill switch (an emergency stop you’ve rehearsed).

The ladder is built around the “excessive agency” risk: a system given more functions, permissions or autonomy than the job needs. Keep tools and permissions minimal, have a human approve high-impact actions, and check permissions in the system behind the model instead of letting the model decide. Logging and rate limits reduce damage; they don’t prevent the error.

Write the conditions for each step up before you need them: copy the table into reports/level-conditions.md, fill in your numbers and commit it before you run anything. If you change it later, write the date and the reason in the file. That stops you loosening the rules on a good day.

Never move up because you’re in profit. A few weeks of P&L contains luck and says nothing about whether the system is safe when something breaks. The criteria are process: tests, logs, rehearsals.

Step up Minimum conditions (you set the numbers) Evidence
0 → 1 Training-data sharing off; AGENTS.md in place; the agent is blocked from reading .env; Git checkpoints /status shows the settings file loaded; git log --oneline shows commits
1 → 2 N sessions with no invented numbers (you pick N); agent decisions in a fixed JSON template checked by code; the lot function has tests and they pass when you run them Session log; pytest output; the criteria file committed before running
2 → 3 (demo only) The code check layer has run for the time you set; the kill switch has been rehearsed; a written stop-conditions table; no open technical incidents Rehearsal log; committed stop table; closed incident list
Live account Outside the scope of this series —

Automating with an agent doesn’t change who is responsible for a trade. An order the agent proposed or the code sent is still your order, and the risk is yours. Check the rules where you live for the instruments and venues you use; this is not legal advice.

Try it: hand over one job through the loop

PART A · paste at steps 1–2 (Plan mode)
Timestamp: [DATE TIME, e.g. 2026-11-11 01:00 UTC]. Folder: [FOLDER, e.g. trading-agent-lab]. Read AGENTS.md first.
Job: [ONE SMALL JOB, e.g. write src/lot.py and tests/test_lot.py].
Spec: lot = risk USD / (SL distance x value per unit per lot), rounded DOWN to the 0.01 step; below 0.01
return 0 (no trade); raise an error if risk or SL distance isn't positive. Conventions: XAUUSD 100 (SL in
USD), EURUSD 10 (SL in pips), BTCUSD CFD 1 (SL in USD).
Check cases: [PASTE THE 5-CASE TABLE].
Step 1: read only. List the relevant files and data, and anything unclear. No edits, installs or network calls.
Step 2: write a plan: files to create or edit (only within [ALLOWED FILES]), order of work, assumptions,
risks, the test command. Stop and wait for my approval.
Rules while building: tests first, then the function; never delete tests or change their expectations;
never hard-code a value to pass a test; don't read .env; add no network calls or order functions; if
something is missing, ask, don't guess.
When reporting done: list the files changed, the test command with its output verbatim, and the hand
calculation for [HAND-CHECK CASE].

PART B · paste at step 5 (read-only subagent or a new session)
You are reviewing code you didn't write. Read only; don't edit files. Compare [COMMIT OR FILE LIST]
with the spec in part A.
Look for: anything that could round UP; unchecked inputs; missing tests (zero or negative input, a
result exactly on a step multiple); hard-coded values; network calls, secret-file reads, order functions.
Return a table: file | line | issue | fix. Report only correctness problems, not style. If nothing is
found, write "not detected".

Key takeaways

  • Five steps: Explore and Plan in Plan mode, Build in Manual, you check and commit, then an independent read-only review.
  • “5 passed” isn’t enough: read git diff on tests/ to see whether the agent changed what the tests expect.
  • Never enable a skip-all-permissions mode, and look at the mode before the first message.
  • Move up the autonomy ladder only when conditions written and committed in advance are met, such as a rehearsed kill switch. A few profitable weeks don’t count.

Comments