Building a C++23 Trading Tool With AI Coding Agents (Without Making Spaghetti)

Taylor Built Solutions Logo

BLUF – AI coding agents will happily turn out thousands of lines of working-looking C++ in an afternoon. Left alone, they will also quietly bake in concurrency bugs, duplicated logic and optimistic assumptions about external APIs. Keeping Kestrel clean came down to two things: automated “house rules” set up early (narrow interfaces, .clang-format, .clang-tidy, sanitizers) and never letting a single AI model grade its own homework.

In this post:

In my last post I introduced Kestrel, a C++23 library and command-line tool for pulling stock and cryptocurrency market data, backtesting trading strategies, paper trading, and placing live orders on Binance.US and Charles Schwab. (A Kraken live venue has just landed and is still waiting on its funded-account order check). One of my two main goals with Kestrel was to find out how far agentic AI coding tools can be pushed on a non-trivial C++ project before the codebase turns into a giant pile of spaghetti.

When I started writing about AI on this blog last year (setting up Ollama and Open WebUI at home, and then why software development isn’t writing code), I was firmly in the camp of engineers who didn’t want LLMs anywhere near production-style C++. Twenty years of maintaining legacy and embedded C++ will make you allergic to “magic” code nobody on the team actually understands. At the same time, burying my head in the sand wasn’t an option either.

I intentionally didn’t hide the AI’s involvement in Kestrel. Almost every AI-written commit title starts with the model (and tool) that wrote it. As I write this, 102 of the first 132 commits carry an Opus 5.5 prefix, 5 are Gemini 4 work reviewed by Opus, 2 are Sonnet 5.5, and 1 carries an OpenCode / GLM-5.3-Flash prefix (plus an earlier GLM review commit). Most of the rest are mine: formatting, the Dockerfile, sanitizer settings and TODO updates.

In this post I’ll walk through which tools and models I used, the multi-model review workflow I settled into, and the C++ guardrails that kept a fast-moving AI-assisted project from collapsing under its own weight.

What AI Coding Agents and Models Did I Use?

Rather than marrying myself to a single vendor or subscription, I rotated across three agentic coding tools and six models:

  • Claude Code running Claude Opus 5.5 and Sonnet 5.5
  • Antigravity running Gemini 4 Carbon and Gemini 4 Argon
  • OpenCode running GLM-5.3 and GLM-5.3-Flash

Each combination ended up with its own personality and sweet spot:

Multi-Model AI Code Review: Never Let One Model Grade Its Own Homework

The thing that helped Kestrel the most wasn’t a clever prompt template. It was pitting different models and tools against each other on uncommitted code.

For a non-trivial feature, my loop usually looked like this:

  1. Write, plus a subagent review, in Claude Code: Opus 5.5 implements the feature or fix (with GoogleTest coverage and doc updates), and a Sonnet 5.5 subagent reviews it first. The Opus agent makes fixes from the review and has Sonnet re-review to see if anything new was introduced.
  2. Cross-tool review in Antigravity: Before committing anything, I copy Claude’s summary of the changes over to Antigravity and ask Gemini 4 (Carbon or Argon) to read that summary and the uncommitted git diff in the working tree, and give me a code review.
  3. Verify and fix back in Claude Code: I paste Gemini’s review back into Claude Code and tell Opus 5.5 to check every finding against the actual code, fix what holds up, and push back on what doesn’t.
Diagram of Kestrel's cross-model AI code review workflow: Opus 5.5 writes in Claude Code, Gemini 4 reviews the uncommitted diff in Antigravity, and Opus 5.5 verifies each finding before tests pass and commit, plus reverse reviews and periodic OpenCode GLM-5.3 sweeps.

I ran the same loop in reverse too: Gemini 4 Carbon or Argon writes the feature in Antigravity, and Opus 5.5 in Claude Code plays the skeptical reviewer. That’s why several recent commits carry two names, like Gemini 4 Carbon / Claude Opus 5.5. Every so often I’d also turn OpenCode with GLM-5.3 or GLM-5.3-Flash loose on a bigger section of the repository to see what the other two had walked past.

Why Cross-Model Code Reviews Work

Why bother copying summaries back and forth between tools when Claude Code can already spawn its own review subagent Because a reviewer with different context finds different things.

When an agent writes a feature, its context window is full of the dead ends it tried, the assumptions it made about an exchange’s API, and its own story of why the approach should work. Even a fresh subagent from the same model family tends to share the same blind spots.

Drop an uncommitted diff and a short summary into a separate tool running a different model family, and that second agent has none of the author’s sunk-cost context. All it sees is what you claimed you changed versus what the C++ in the working tree actually does. Over and over, the second model asked uncomfortable questions like:

  • “What happens if this order partially fills right before it expires?”
  • “What happens if a drawdown limit trips on a stock position at 5:30 PM, when the market is closed?”
  • “Does Kraken take a sell order’s fee from the base asset or the quote asset by default?”

The other half matters just as much: I didn’t let the author model blindly accept every review comment either. LLMs love to be agreeable (“You’re absolutely right!”), which is a great way to introduce new bugs during a code review. Every finding had to be checked against the code and real exchange behavior before anything changed.

Two examples from Kestrel’s history stand out:

  • During one project review, a reviewer flagged that Kestrel’s database wrapper didn’t automatically re-run a SQL statement if the PostgreSQL connection dropped mid-call, and that the backtester didn’t reject cached bar series with time gaps in them. Checking both against reality showed why leaving them out was right. Blindly re-running a statement after a lost connection can insert a fill twice. And exchanges have real maintenance outages that leave permanent gaps in historical bars, so a gap check would have every backtest re-downloading history forever.
  • When testing Fair Value Gap setups across crypto and stocks, Opus re-ran Gemini’s standalone research simulation with its own independent code and found two simulator mistakes. One filled resting buy limits at the limit price even when a bar gapped open below it and the stop, which made losses look worse than they were. The other compared the gap entries against a control that bought at a shallower pullback. With fills at the open (the way Kestrel’s own backtester already does it) and the control at the same depth, the gaps filled and bounced like any other three-bar move of the same size, and none of the variations beat simply holding the same coins and stocks. Neither model’s first read of the results would have held up on its own. (As always, none of this is financial advice.)

C++ Guardrails for AI Coding Agents (How Not to Make Spaghetti)

Cross-model reviews catch logic flaws, business-rule edge cases and bad assumptions. What they won’t save you from is structural drift, if the codebase doesn’t have mechanical guardrails.

Right after the initial commit I hit pause on new features to set the ground rules for naming and formatting. The rest of the guardrails were layered on over the next three weeks: the offline Docker environment, then sanitizers, then CI, then clang-tidy. From the day each one landed, every change, mine or an agent’s, had to get past it.

1. Clean Interfaces and One-Way Dependencies

Spaghetti happens when everything is allowed to talk to everything else. As I covered in the introduction, Kestrel follows the same three-step loop I used on embedded control systems (read inputs, decide, write outputs), held in place by strict interfaces:

  • Strategies only see Strategy hooks and a Context interface. They know nothing about HTTP, JSON, WebSockets or SQL, or whether they’re talking to Binance.US, Kraken, Schwab, PaperTradingVenue or ReplayDataSource.
  • WebSocket threads only push incoming events onto a queue. A single Runner thread hands them to the strategy one at a time, so strategy code isn’t littered with mutexes.
  • Dependencies flow one way (app -> factory -> domain interfaces), and early on I stripped main.cpp down to thin CLI11 subcommands so almost the whole application lives in libkestrel, where GoogleTest (kestrel_tests) can hammer on it directly.

Narrow interfaces keep agents on a short leash. When adding a strategy or an exchange means implementing one well-defined header, with fakes ready for the tests (RecordingVenue, FakeTradeLog and RoutedHttp), an agent has a much harder time tangling unrelated parts of the system together.

2. Formatting and Readability Rules in the First Few Days

When three model families edit the same C++ files, style consistency goes out the window unless a machine enforces it. The second commit and the fourth set the rules:

  • Class member variables follow the mVariable pattern, so member state jumps out when you’re reading a diff.
  • Every if statement, even a one-liner, was supposed to get braces on separate lines for human readability (and so nobody pulls a goto fail during a merge). I did a pass on day one to add them, forgot to turn off Google style’s single-line if allowance in .clang-format, and the agents quietly slipped a hundred unbraced early-returns back in over the next month. Point proven: agents only keep style rules a machine actually enforces.
  • A .clang-format file based on the Google C++ style keeps whitespace, includes and alignment identical no matter which agent wrote the code.

3. Compiler Warnings and a Signal-Only .clang-tidy

Every target (kestrel, kestrel_app and kestrel_tests) compiles with -Wall -Wextra -Wpedantic, and the Docker test container and CI add -Werror (-DKESTREL_WERROR=ON), so a new warning breaks the build.

On top of that, I added a .clang-tidy configuration that turns on the clang-tidy check families that actually find C++ bugs: bugprone-*, performance-*, concurrency-*, clang-analyzer-*, cppcoreguidelines-* and misc-* (minus the style-only rules).

Side Note: If you turn on every clang-tidy rule in a modern C++23 codebase and hand the output to an AI agent, it will happily spend hours mangling clean code to silence style nits. Kestrel’s first pass gave 556 warnings. None were live bugs, a handful were worth hardening, and the rest were noise. We fixed the handful and turned the noisy checks off right in .clang-tidy, with a comment on each saying why. For example, bugprone-unchecked-optional-access flagged 158 spots, and every one we sampled was already guarded by a container or an earlier check it couldn’t see. The hardening:

  • Made the base interfaces non-copyable, since their implementations stop background streams in their destructors and a copy would stop a stream twice;
  • Marked the stream classes final, so a destructor’s Stop() call can’t miss an override;
  • Zeroed struct members that had been left uninitialized;
  • Added top-level exception logging in main, so an escaping error can’t end in a silent std::terminate.

4. Sanitizers (ASan, UBSan and TSan)

C++ will let code compile cleanly, pass its tests nine times out of ten, and still hide undefined behavior or data races. In CMakeLists.txt, -DKESTREL_SANITIZE=address,undefined and -DKESTREL_SANITIZE=thread instrument Kestrel and the dependencies it fetches with AddressSanitizer, UndefinedBehaviorSanitizer or ThreadSanitizer. -fno-sanitize-recover=undefined makes undefined behavior abort the test on the spot instead of printing a polite warning and carrying on.

ThreadSanitizer paid for itself on its very first run. Kestrel’s Runner, WebSocket streams, venue pollers, and QuoteWriter all run on their own threads, and TSan immediately flagged a race in our own test harness: a RunnerTest polled log->snapshots.size() from the main test thread while Runner::Run() was appending to that same FakeTradeLog on the runner thread. Without TSan, that kind of bug sits quietly until it corrupts memory on some random CI run months later.

5. An Offline Docker Sandbox (--network none)

Letting an agent run shell commands to build and test a live-trading application has an obvious hazard: you really don’t want a test run touching live exchange endpoints or reading real API keys.

So Kestrel has an Ubuntu 26.04 Dockerfile that pre-installs GCC, CMake, Ninja, linux-perf, IXWebSocket, and PostgreSQL 18 with TimescaleDB. It sets up a non-superuser kestrel_test database when the image is built, and then, when the container runs, builds Kestrel and runs all 1,000+ tests with the network unplugged. That includes the database integration tests, which use real market data checked in under tests/data/market/:

docker build -t kestrel-test .
docker run --rm --network none -v "$PWD":/src kestrel-testCode language: JavaScript (javascript)

GitHub Actions CI runs the same --network none container on every push. If an agent writes a test or startup path that reaches out over the network instead of going through a fake or a fixture, it fails right there, every time.

6. docs/ and TODO.md as External Memory

An underrated trap with AI coding agents is amnesia. Every session starts fresh and, if your design rules only live in yesterday’s chat, today’s agent will happily invent a second way of calculating P&L or parsing the config file. Additionally it provides me a way of reasoning about the code when much of it was written by a model.

In Kestrel, documentation isn’t written at the end of a milestone. It’s part of the definition of done for almost every commit:

  • docs/design.md lays out the thread model, the data flow and which class owns what (PnlTracker is the single average-cost calculation; factory.cpp is the only place that maps config names to concrete classes).
  • docs/strategies and docs/venues provide locations for documentation of strategies and venue specific gotchas.
  • TODO.md tracks priorities, in-progress checklists (like the real-account checks for Schwab and Kraken), known limitations, and notes on why certain ideas were tested and rejected, so a future session doesn’t suggest them all over again.

Real Live-Money Bugs Caught Before They Cost Anything

To make this concrete, here are a few real bugs that cross-model reviews and scripted tests caught before they could bite a live account:

  • Refusing to sell during a risk halt on Binance.US: When RiskGatedVenue trips a halt or the daily loss limit, it blocks new entries and only lets through sells up to what’s currently held. On the paper venue, GetPositions() reports holdings. Binance.US spot has no “positions” endpoint, though, so it came back empty. During an emergency halt on Binance.US, the risk gate saw 0 held and refused the protective sell trying to close what the run had just bought! Cross-review caught it, and the gate now counts the larger of the venue’s positions and what has filled during the run.
  • Manual CLI orders skipping [risk]: The Runner wrapped venues in RiskGatedVenue, but the standalone kestrel_app order command originally talked straight to the raw venue. That skipped max_order_notional and the symbol allowlist unless you kept every rule in your head. It now goes through ManualOrderLimits by default (--test orders included).
  • Partially filled entries left unprotected: PaperTradingVenue fills stop orders whole, which hid a live-venue bug in the breakout strategy. If an entry partially filled on a real order book and the rest expired or was cancelled, that partial position could sit open with no protective stop. Review caught the hole in the state machine, and the fix came with scripted partial-fill tests.
  • Fee drift on Kraken: By default, Kraken takes a sell’s fee out of the base asset (the coin), while fill reports state the fee in the quote currency. Kestrel’s position tracking would have drifted a little on every sell. Now every Kraken order passes oflags=fciq to take the fee in the quote currency, and PnlTracker takes any fee paid in the base asset off what’s held for the cases where one still happens.

Conclusion

Back in the summer of 2025 I wrote that software development isn’t writing code. Building Kestrel with AI coding agents has provided great evidence for that.

Opus 5.5, Sonnet 5.5, Gemini 4 Carbon and Argon, and GLM-5.3 and its Flash variant turned months of C++23 boilerplate, exchange REST and WebSocket plumbing, SQL migrations and test scaffolding into weeks. But my job didn’t turn into clicking “Accept All.” Nearly all of it moved into the parts of engineering that actually prevent spaghetti: designing clean interfaces, setting up ruthless automated checks (.clang-tidy, ASan/UBSan/TSan, offline Docker tests), running reviews across models that don’t share each other’s blind spots, and checking every claim against recorded data and the real APIs.

Next up in the Kestrel series is C++ Under the Hood: Money, Latency, and Safety. I’ll cover fixed-point Decimal math with __int128, why Kestrel never blindly retries a timed-out order placement, how keeping HTTPS connections open cut the median call to Binance.US’s servers in Tokyo from about 430 ms to 130 ms, and keeping TimescaleDB fast with a steady stream of quotes coming in.

Have you tried pitting AI models against each other in code reviews on your own projects, or found other guardrails that keep agents honest in C++? Let me know in the comments or reach out. I’d love to hear what’s working (and what isn’t) for you!

Leave a Reply

Your email address will not be published. Required fields are marked *