← Resources The Trdrbot Loop — a standalone document, hosted as-is
trdrbot · how the system works

The Trdrbot Loop

An autonomous options-trading agent, explained from the top down — the loop, then each stage, then one real trade traced end to end, then every subsystem by name.

Start here: what this actually is

trdrbot is a program that wakes up every 60 seconds, looks at the market and the news, and occasionally decides to buy or sell an options position through a broker — on its own, with no human in the loop. It runs on a paper trading account: real market data, simulated money.

The one idea everything else follows from. Most trading bots score themselves on profit. Over a single week, profit is mostly luck — we measured it: an agent with a genuine skill edge only beats a coin flip about 69% of the time over 20 trades. So a bot that learns from profit alone will happily learn superstitions.

trdrbot instead separates two questions that profit blurs together: "was my view of the world right?" and "was the trade I built to express it right?" It scores those separately — and when it makes money on a view that turned out to be wrong, it deliberately learns nothing from it, and that trade is barred from earning it permission to bet bigger.

Everything below is machinery in service of that: three different ways of coming up with an idea, arithmetic that refuses to flatter a bad one, and a scoring loop that only counts evidence that actually teaches something.

The loop at a glance

Four stages run in a fixed order, over and over. The expensive thinking happens rarely; the cheap safety checks happen constantly.

what it learned shapes the next cycle what it saw one action outcomes SENSE look at the world no AI · every 60s CLICK TO OPEN THINK form + price a plan AI · every 15 min CLICK TO OPEN ACT place + verify no AI · every 60s CLICK TO OPEN LEARN guard + score no AI · every 60s CLICK TO OPEN REMEMBER — the shared memory Alpaca Journal Wiki elfmem four stores, four different questions — every stage reads and writes here

↑ click any stage to open it — or press Tab, then Enter

Stage 1 of 4 · runs every 60 seconds · no AI

Sense — look at the world

Collect information and compute every number that doesn't need judgement.

How it works

A sensor is a declared source of information — Alpaca's market data, Alpaca's news feed, Polymarket's prediction-market odds. Each declares how often it runs, how much to trust it, and how to filter what it finds. Everything they return lands in a single inbox as typed items. In parallel, pure-Python analytics recomputes the state of the book: current prices, per-position Greeks, and total portfolio exposure.

Example At 17:32 on 28 Aug, the Alpaca news sensor picked up coverage of Fed Chair Warsh's Jackson Hole speech and wrote it into the inbox. At the same tick, analytics recorded SPY at 769.05 with implied volatility at 10%. Neither step involved an AI model — one is a fetch, the other is arithmetic.
Why it's built this way Adding a new information source should never mean rewriting the pipeline — it's one registry entry. And if a source is down or slow, that sensor is skipped and the rest of the tick continues: one broken feed can never stop the system from managing open positions.

The actual subsystems

sensors registry polymarket odds news_extract structuring analytics book state market_stats technicals inbox queue
Stage 2 of 4 · runs every ~15 minutes · the only routine AI cost

Think — form a plan and price it

Turn information into a falsifiable thesis, then into a specific, sized trade — or, very often, into a documented decision to do nothing.

Part 1 — three ways to have an idea

Three independent generators propose trade ideas. They exist separately because each is blind in a different way, and all three feed one shared inbox with one shared admission gate.

Research top-down · daily regime + news + odds on a fixed watchlist Discovery bottom-up the news names a company, gates filter Muse deliberate randomness two unrelated ideas, forced together one inbox one gate · no favourites
Research can only find what its watchlist points at. Discovery can only find what's in the news. The Muse exists to find what neither would ever look for.
Example — how the Muse works It picks two unrelated concepts from the system's own knowledge base, adds recent news, and forces the question "if this is true, who does it hurt or help three steps later?" Every candidate it invents must then survive a deterministic gauntlet — real price history, a liquidity check, a probability sanity check — before it's allowed anywhere near a decision. Only the top 2 per run survive.

Part 2 — inside one decision

When the decide cycle runs, the AI's job is deliberately narrow: state a thesis, propose at least two genuinely different ways to trade it, and state an honest probability. Everything after that is arithmetic it doesn't get a vote on.

simulate_experiments prices every candidate facts vs. estimates, costs charged upfront size_position how many contracts — Kelly, shrunk by its own track record record_position writes the exit rules and locks the thesis in, to be scored later
The model supplies judgement. The code supplies every number.
Why "at least two structures" If the agent could simulate one idea and stop, that's just a slower way of deciding first and justifying afterwards. Requiring a genuine comparison forces the choice to actually happen.

The actual subsystems

research top-down discovery news-led muse collision opportunity the gate experiments compare optmath options maths sizing Kelly competence size ladder llm model gateway
Stage 3 of 4 · reconcile every 60s · orders only on a decision

Act — place the order, then verify reality

Submit through Alpaca, then continuously check that what we think we own matches what the broker says we own.

How it works

Orders go through the Alpaca MCP server — one connection shared for a whole tick rather than reopened for every call. Every order carries an ID computed deterministically from the decision that caused it, so if the process crashes and retries, it resubmits the same order instead of accidentally opening a second position. Then, every single tick, the reconciler diffs the broker's actual holdings against trdrbot's own records.

Example The SPY order was submitted at 17:34. Seven minutes later, reconciliation confirmed the legs were really there and stamped the position verified by trdrbot/reconcile — the position went from "we think we placed this" to "the broker agrees this exists."
Why reconcile runs FIRST, before anything else Options can be assigned or expire without asking you. If the exit-rule checker ran first, it could act on a position the broker had already closed hours ago — selling something you no longer own. Running reconciliation first means the ordering itself prevents the bug, rather than a check bolted on to catch it.

The actual subsystems

mcp_client Alpaca link tool_guard order IDs reconcile broker truth positions status machine lock one tick at a time
Stage 4 of 4 · guards every 60s · scores at the thesis horizon

Learn — guard the position, then judge it honestly

Enforce the exits the agent promised, and afterwards work out what — if anything — the outcome actually taught.

Part 1 — the guard

When the agent opens a position it must also write its own exit conditions. A deterministic evaluator then checks them every 60 seconds — far faster than the AI runs — and closes the position when one triggers. Crucially, thesis-level stops watch the underlying stock price, not the option's own quoted price, which on a thin option can swing wildly for no real reason.

Example — the live SPY position's five rules Stop loss at −65% · profit target at +140% · close on expiry day · and a thesis stop: close if SPY trades above 776 — the exact level the agent said would prove its view wrong. Plus one rule it can't override: close if a leg disappears at the broker.

Part 2 — the scoring that makes profit honest

At the thesis's own stated deadline — not when the position closes — the system asks two separate questions, and the four possible answers are treated very differently.

THESIS HELD THESIS FAILED PROFIT LOSS right, and well-built reinforce both LUCK learn nothing cannot earn size view was fine build was not fix the structure honest miss faithful build correct the view
The top-right cell is the whole point: a profit on a view that turned out wrong teaches nothing, and is excluded from what earns the agent permission to trade bigger.
Why size has to be earned Position size is set by a four-tier ladder. Climbing it needs resolved theses, demonstrated calibration (when it says 70%, does it happen 70% of the time?), and — the unusual part — a high attribution rate: proof the agent could explain why it was right. A losing streak demotes it immediately.

The actual subsystems

exit_rules the guard attribution view vs build calibration Brier score ledger pre-registration learn credit assignment coach self-improvement health silent-failure alarm
The shared layer · every stage reads and writes it

Remember — four stores, four different questions

Deliberately not one database doing four jobs, because the four jobs have genuinely different rules.

Alpaca"What do I actually hold?" The broker is the only authority on this. Real-time, external, and always trusted over our own records.
Journal"What happened, in order?" An append-only log, never edited. Every decision is written here before the order is placed, so a crash can always be reconstructed.
Wiki"What's the story?" Human-readable pages: one per position with its full thesis, plus market context and accumulated lessons.
elfmem"What do I know that matters right now?" Evolving memory whose confidence in each stored pattern moves with real outcomes.
Why this matters Every tick is a cold start — nothing is held in memory between runs. Continuity lives entirely in these files, which is why the system can be killed and restarted mid-week and lose nothing but the seconds it was down.

The actual subsystems

journal event log wiki narrative store elfmem_adapter memory constitution principles lessons seeded knowledge store atomic writes

A worked example: one real trade, start to finish

This is an actual position the system opened on 28 August 2026 — real numbers, taken from its own records. Step through it to see all four stages do their job.

Sense · 17:32

Something happens in the world

The news sensor picks up coverage of Fed Chair Warsh's Jackson Hole speech. Fed funds futures have flipped to price a September rate hike as more likely than a hold — roughly 60%. Gold, Bitcoin and long-dated Treasuries all sell off.

At the same moment, analytics records the market state — no AI involved, just arithmetic.

SPY spot 769.05 implied vol 10% recent run +5.7% over 21 days
Think · the thesis

The agent forms a falsifiable claim

It notices a mismatch: everything else repriced for a hike, but SPY is only −0.3% after touching 775. Its view is that equities have barely discounted the news.

"I expect modest multiple compression, SPY drifting to ~758–765 by 9/3. INVALIDATED if SPY makes new highs above 776 — that says the tape has decided a hike-on-strength is fine, and the premise is dead."

Note what makes this a thesis and not a hunch: it names a target range, a deadline, and — most importantly — the exact price that would prove it wrong.

claim band 745 – 766 horizon 2026-09-03 expected move -0.9% invalidation SPY above 776
Think · pricing

Several ways to trade it, priced honestly

The agent must propose at least two genuinely different structures. Each is priced with trading costs charged up front, not after — because at this scale the cost of getting in and out is often the same size as the entire edge.

The winner is a bear put spread: buy the SPY 766 put, sell the 758 put, both expiring 3 September. Buying one and selling the other caps both the cost and the maximum possible loss.

structure SPY 766/758 put spread breakeven 764.33 (−0.6%) payoff 2.85 : 1 after real costs
Think · sizing

How big? Not the agent's choice

The agent states its honest probability; the code decides the size. That probability is shrunk toward its measured track record — an agent that has not yet proven itself gets a fraction of what its confidence would otherwise justify.

The result is checked against three caps at once: this position, this underlying, and the whole book — all measured in dollars that can actually be lost.

contracts 13 max loss $2,171 ← the true worst case, fixed at entry theta −$182 / day vega +$218 per vol point
Act · execution

Placed, then verified against the broker

The order goes out through Alpaca's MCP server at 17:34, tagged with an ID derived from the decision itself. The decision was written to the journal before the order was sent — so if the process died mid-flight, a restart would find the record and resume the same order rather than open a second one.

Seven minutes later, reconciliation confirms the broker really shows both legs.

17:34:00 order submitted 17:39:23 verified by trdrbot/reconcile status open (broker agrees)
Learn · the guard

Five rules now watch it, every 60 seconds

The agent wrote these itself at entry. From this point they run without it — no AI call needed to close a position that has gone wrong.

stop loss −65% profit target +140% time stop close on expiry day thesis stop SPY above 776 ← the invalidation level system rule close if a leg vanishes at the broker

The thesis stop is the interesting one: it watches SPY itself, not the option's price. The agent said 776 would prove it wrong, so 776 is what gets watched.

Learn · the verdict

On 3 September, two separate questions

At the thesis's own deadline — not when the trade closed — the system asks:

1. Was the view right? Did SPY actually land between 745 and 766? That's a yes/no about the world, and it's the question that moves the calibration score.

2. Was the structure right? Given what the market did, was a 766/758 put spread a good way to express it?

If it made money but SPY finished at 790, the answer is: this was luck. The system records that plainly, learns nothing from it, and that trade cannot count toward earning the right to trade bigger.

at horizon 2026-09-03 scored on did the BAND hold, not did it profit feeds calibration · attribution rate · the size ladder
And the trades it turns down Most of what the agent does is decline. Here it is refusing a tempting-looking credit spread, in its own words from a live run:
"Both negative after costs, so I stopped before size_position. The call credit spread is exactly the trap: collect $51 to risk $449 needs ~90% accuracy to break even […] Call-side IV is 7.4% vs put-side 16.5% — selling upside calls here means selling the cheap wing of a heavily skewed surface into an earnings print."

Every subsystem, by name

The concepts above map onto real modules. This is the whole system — roughly 45 modules, grouped by the stage they serve.

Sense — gather and compute

sensorsThe registry of information sources. Adding one is an entry, not new code.
polymarketPrediction-market odds — crowd probabilities, free and unauthenticated.
news_extractTurns raw headlines into dense structured signal with citations.
evidenceThe shared "what do I look at first" gatherer used by all three thesis sources.
analyticsPortfolio state, per-position Greeks, beta-weighted book exposure.
market_statsTechnicals, realized volatility, and a bootstrap Monte Carlo from real history.
inboxThe file queue everything lands in — also the system's main testing seam.

Think — decide

researchDaily top-down cycle: regime → company dossiers → falsifiable opportunities.
discoveryThe news nominates companies; a deterministic gauntlet filters before any write-up.
museCreative collision — unrelated concepts forced together, then adversarially gated.
opportunityThe single admission gate all three sources must pass through.
experimentsThesis → candidate structures → ranked, comparable results.
optmathOptions maths, split hard into exact facts vs. modelled estimates.
sizingKelly on the conditional payoff, shrunk by measured calibration.
competenceThe four-tier ladder: size is earned by resolved, explicable results.
local_toolsThe three tools the agent actually calls: simulate, size, record.
llmModel gateway with an ordered fallback chain across providers.
compactShrinks heavy tool results before they ever reach the model's context.
idleWhat to do when nothing has happened — sleep, review, or hunt.
tickThe loop itself: what runs every 60s, what runs every 15 minutes.

Act — execute

mcp_clientOne Alpaca MCP session per tick, not one per call.
tool_guardForces deterministic order IDs so a retry can't double a position.
reconcileBroker truth vs. our records — and it runs first, every tick.
positionsPosition pages and the status machine that guarantees one resolution.
lockSingle-flight tick lock, breakable if a previous run died.

Learn — guard and score

exit_rulesThe agent's own commitments, executed every 60s against the underlying.
attributionThe view-vs-structure verdict, at the thesis horizon.
calibrationBrier score and Murphy decomposition on every stated probability.
ledgerPre-registration: every thesis recorded, traded or not.
learnCredit assignment — which memories and sources get reinforced.
coachPaired A/B trials on its own prompts; promotes only on real evidence.
housekeepingRuns while markets are closed: interim scoring, memory consolidation.
healthAsks of every subsystem: did it run and produce, or run and do nothing?
reportOne self-contained HTML page: gauges over time with the Coach's actions marked.

Remember — the substrate

journalAppend-only event log; decisions written before orders are sent.
wikiPosition pages, market context and lessons, in a documented format.
elfmem_adapterEvolving memory whose confidence moves with scored outcomes.
constitutionTen epistemic principles — how to reason, remember, and change.
lessonsMeasured lessons seeded into memory, each carrying its own numbers.
storeAtomic writes, so a crash mid-save can't corrupt a state file.

Chassis — keeping it alive

configOne place for models, watchlist, cadences and secrets.
cliEvery human-facing command: doctor, health, report, calibration, coach.
usageToken and cost accounting across every provider and role.
failuresClassifies errors so a transient blip isn't treated like a permanent one.
idsThe provenance spine — one ID threading a position through every store.
promptsFingerprints every prompt, so decisions stay comparable across changes.
trdrbot · paper trading, real market data · numbers in the worked example are taken from the system's own position records for 2026-08-28