2026-10-13
Study trading software you are allowed to inspect
REA (Reverse Engineer Anything) is a local Model Context Protocol (MCP) path for authorized inspection: behavior, code paths, and dependencies of software you may actually open. This page uses that path as the observation layer of a one-person research desk for trading systems — then a separate, reviewable agent loop that writes Python hypotheses and a small Rust risk shell. An Opus-class reasoning model can draft the words and the diffs. It does not get order keys, and this page prints no return, Sharpe, drawdown, or profit figure.
Install the tools with the site guide /docs/install/ (teaching pin npx -y [email protected]; re-check npm before you automate). Client wiring lives on /docs/mcp-clients/. Community investigation shape: /showcase/rea-investigate/ (Plan, Trace, Verify, Report). Case catalog: /showcase/.
What the figure is asking you to do
The picture under the title is a pipeline, not a promise. Walk it as six gates. A candidate that fails a gate goes back to evidence or to a written rejection. It does not skip ahead because a chart looked smooth.
| Gate on the figure | Desk meaning | You may proceed when |
|---|---|---|
| Authorized target | Public behavior of a program you may inspect, or an artifact you control | The authorization note is in the experiment folder |
| REA + MCP | Inspect, trace, collect Evidence | Findings cite a path, symbol, or trace id, and unknowns are labeled |
| Independent model | Your code, not a paste of someone else's strategy text | A unit test encodes the rule without a live account |
| Quant validation | Costs, chronology, holdout | The fee grid and the time split below are filled in |
| Pass / reject | Fail closed | A failed row names the gate; it does not get retuned on the holdout |
| Paper trading | Forward behavior on a simulator you control | paper_only is still true |
| Audit | Every try, including rejects | The log gained a row before the run |
A cost identity, not a performance claim
Gross price change is not a reason to deploy. Keep one identity for every experiment and use the same unit on every term (this page uses basis points of notional, bp; 1 bp = 0.01% = 0.0001 of notional):
R_net = R_g - C_f - C_s - C_m - C_o
| Symbol | Name | Where the number comes from |
|---|---|---|
R_g | Gross strategy result | Your mark-to-decision-price rule, before costs |
C_f | Explicit fees | The fee schedule of your account: commission, exchange, regulatory |
C_s | Slippage | Distance from the decision price to the modeled fill |
C_m | Spread and impact | At least half the bid-ask when you cross; plus a stress you add |
C_o | Other operating cost | Borrow, funding, data, or anything you pay that is not in the three cells above |
R_net | Net | Arithmetic only. A positive R_g can still produce a negative R_net |
Calculator rows (inputs you type, not measurements). Nothing in this table was backtested on a market. The gross cells are placeholders so the subtraction can be checked.
| Cell | Calculator A | Calculator B |
|---|---|---|
R_g | 12 bp | 30 bp |
C_f | 20 bp | 2 bp |
C_s | 1 bp | 1 bp |
C_m | 0 bp | 1 bp |
C_o | 0 bp | 0 bp |
R_net | −9 bp | 26 bp |
Calculator A is the teaching point: a positive gross of 12 bp becomes −9 bp after a 20 bp fee (10 bp per fill, entry and exit) and 1 bp of slippage. Calculator B is still only arithmetic — the 30 bp gross is not a result this site claims you can earn. Two taker fills at 0.10% each are 10 bp + 10 bp = 20 bp round trip before spread, because 0.10% = 10 bp. Some published retail spot schedules have sat near 0.10% per fill at the base tier. Open the current PDF or CSV for the account you use. Do not hard-code 0.10%. Futures and cash-equity schedules are often tighter and are account-specific.
Authorization before any tool call
Inspection and a research agent are allowed here only inside a written scope. The interesting engineering (order lifecycle, market-data handlers, risk predicates) is available on software you already control: your bot, your paper gateway, an open-source engine whose license allows reading, or a vendor build your contract lets you analyze.
| Target | On this page | Stop |
|---|---|---|
| Source you wrote | Map functions and config | Keep secrets out of the prompt log |
| Open-source strategy or engine code, license permits reading | Trace and reimplement ideas in your own words | Respect the license; do not republish large verbatim trees |
| Binary you compiled, or a vendor binary under a contract that allows inspection | Hash it, then BYO a licensed decompiler | Disposable VM if you did not build it |
| Employer or client system with written permission | Stay inside the named paths and the retention rule | Do not copy Evidence out of that permission |
| Someone else's prop terminal, broker app, or venue binary without permission | Out of scope | /faq/legal-boundary/ |
| License cracks, DRM bypass, credential theft, live probing of a venue | Out of scope | /compliance/ |
Preflight, in order:
- Write one sentence of authorization: owner, path, date, and whether paper trading is allowed.
- Pin the tool:
npx -y [email protected](site teaching pin as of the 6.4.0 ops guide). Savedoctor --json. - Record SHA-256 of every artifact you open.
- Put API keys with trade or withdraw scope out of the agent environment. A paper simulator key, if you need one, is a separate secret with no withdraw right.
- If the client caps MCP schema size, set
REA_MCP_INPUT_SCHEMA_PROFILE=compactand reconnect. See /blog/rea-agents-6-4-0/ and /faq/mcp-schema-size/. - Read /blog/rea-agent-security-posture/ before you register MCP on a machine that also holds production credentials.
Six stages
Treat the list as a checklist you can tick in the experiment log. Stages 1–3 are REA work on the authorized artifact. Stages 4–6 are research you own. Mixing them in one chat without a log is how unknowns turn into folklore.
| # | Stage | Question | Artifact you keep | Fail closed when |
|---|---|---|---|---|
| 1 | REA workflow | What does this program do, and along which paths? | Dependency map + Evidence ids | The answer has no location |
| 2 | Source and binary | Which functions implement that path? | Path:line or address, plus unknowns | The prompt asks to bypass a license check |
| 3 | Behavior | How do submit, cancel, market data, and fills line up? | Event table joined to stage 2 | The session sent a live order |
| 4 | Hypothesis | What rule would explain the evidence, and how do we falsify it? | Python test + optional Rust shell | The model invented a fill |
| 5 | Backtest method | Does the rule survive costs and a time split? | Fee grid, slippage note, holdout count | Parameters were chosen on the holdout |
| 6 | Research loop | What failed, and which limit binds? | Append-only log + risk struct | A human has not read the row |
1. REA workflow
Point the MCP client at a local REA server and give an absolute path to the tree you are allowed to read. Ask for mechanisms. A useful first session has four questions and zero orders:
- Where is an order message built (side, quantity, price, time in force)?
- Where is a cancel built, and which id joins it to the submit?
- Which handler consumes a market-data update, and which fields does it trust?
- Which local predicate can reject an order before it leaves the process?
Pass and fail look different:
| Ask | Pass | Fail |
|---|---|---|
| Where is an order built? | File, function, and an Evidence id | "Somewhere in the trading module" |
| What sets fees? | Config path, key, and the literal default | A guessed commission |
| What updates the book? | Handler name and field list | A paragraph about how markets work |
| What rejects locally? | The predicate and its location | The words "risk management" with no condition |
REA does not ship a decompiler. Ghidra, JEB, and IDA stay bring-your-own and licensed. Setup may offer Hopper only with approval. Details: /faq/setup-vs-providers/, /blog/ghidra-mcp-with-rea/, /faq/what-can-i-analyze/.
A prompt that matches this page (edit the path; do not widen the scope):
Authorization: I own /abs/path/to/paper-gateway (source). Paper simulator only.
Pin: [email protected]. Use REA MCP. Return Evidence with path:line.
Questions: order build, cancel id, market-data handler, local reject predicate.
List unknowns. Do not propose live orders, credentials, or license bypass.
Preferred investigation rhythm on this site is the same one documented for /showcase/rea-investigate/: plan, trace, verify, report. The Windows-oriented lab notes on /showcase/rea-lab/ are a separate pin-and-doctor example, still limited to exercises you are allowed to run.
2. Source and binary, authorized artifacts only
Source you may read and a binary you may open are the same scientific job with different viewers. Hash first. Then ask REA to recover structure: modules, types, and the call path from "user or strategy said trade" to "bytes left the process" or "the simulator accepted a paper order".
sha256sumthe tree or the binary. Store the hash in the log before any conclusion.- Source: request a module map (market data, order, risk, UI or CLI) with paths.
- Binary you built, or a contracted binary: open it in your licensed Ghidra, JEB, or IDA. Ask REA for the functions on that same path. Import compiler specs before auto-analysis when the Ghidra guide says so.
- Keep the untrusted binary in a disposable VM. Process capture is not a sandbox (/blog/rea-agent-security-posture/).
- Every claim is either a location or an explicit unknown. Chat prose does not upgrade itself to Evidence (/blog/evaluating-rea-claims/).
- If the license or the terms forbid reverse engineering, stop. Do not negotiate that boundary inside the prompt.
Output you should be able to file:
| Field | Example shape (not a real program) |
|---|---|
| Artifact | paper-gateway @ SHA-256 recorded in the log |
| Order build | oms/build.rs function build_limit |
| Cancel join | Client id field cid, unsigned 64-bit |
| Market data | md/parse.rs handler on_bbo fields bid, ask, ts |
| Local reject | risk/gate.rs returns err when qty == 0 |
| Unknown | Whether ts is exchange time or local time — not yet shown |
That last row is a successful unknown. Filling it with a guess is a failed stage.
3. Behavior: submit, cancel, market data, execution
Mechanics show up as events. Run your paper gateway or a simulator you control. Do not place live orders to watch a venue react. Join each event to a stage-2 location when you have one.
| Event | Minimum fields | Why you keep them |
|---|---|---|
md_update | ts_exchange, ts_local, symbol, bid, ask, last | Decision price and clock skew |
order_submit | client id, side, qty, limit, time in force, ts_local | The intent |
order_ack | client id, venue or sim id, status | The join key |
order_cancel | client id, reason | Lifecycle, not a guess |
exec | price, qty, liquidity flag if the sim has one | The fill you will charge costs against |
reject | code, text, which predicate fired | Distinguishes a local gate from a sim reject |
Clock hygiene. Store both timestamps. If a paper simulator on the same machine shows |ts_local − ts_exchange| greater than 1 second, fix NTP or the parser before anyone writes a latency sentence. One second is a desk threshold for "this session is too dirty for latency talk", not a measurement of edge.
Book hygiene. Drop rows with non-positive prices or a crossed book (ask < bid) and count the drops. A silent drop changes the sample; a counted drop is a field in the log.
Correlation you actually want: UI or strategy call → function from stage 2 → order_submit row → ack → optional cancel or exec. If any arrow is missing, the behavior section lists it under unknowns. It does not invent a matching engine you have not seen.
4. Research agent: Python hypothesis, Rust shell, Opus-class writer
Stage 4 turns Evidence into something a test can reject. Split the jobs so a fluent model cannot skip the gate.
| Piece | Who | Owns | Does not own |
|---|---|---|---|
| Observation | REA MCP | Evidence, paths, unknowns | A story about profit |
| Writer | Opus-class model, pinned model id | A hypothesis sentence and a diff | Order keys, the holdout, permission |
| Hypothesis | Python | The rule, the cost identity, deterministic tests | Live I/O |
| Risk shell | Rust | paper_only, caps, append-only log | A decompiler or a venue exploit |
| Human | You | Authorization, the fee CSV, reading the diff | Blind trust of model prose |
"Opus-class" here means a frontier reasoning model you pin by the vendor's model id. An Anthropic Opus-family id is the usual example. Write the id into the experiment row. This page does not score models and does not claim any of them produces a tradable edge. If you swap models, you change the row; you do not edit history.
Python holds the identity so a one-line test can audit the calculator. The quote in half_spread_bps is invented.
def net_bps(gross_bps, fee_bps, slippage_bps, impact_bps, opex_bps):
"""Same unit on every argument. This function does not know a market."""
return gross_bps - fee_bps - slippage_bps - impact_bps - opex_bps
def half_spread_bps(bid, ask):
mid = (bid + ask) / 2.0
if mid <= 0 or ask < bid:
raise ValueError("bad book")
return ((ask - bid) / 2.0) / mid * 10000.0
def test_calculator_A():
assert net_bps(12, 20, 1, 0, 0) == -9
def test_toy_quote_half_spread():
# Decimal truth: 0.01 / 100.01 * 10000 = 10000/10001 bp ≈ 0.9999
got = half_spread_bps(100.00, 100.02)
assert abs(got - (10000 / 10001)) < 1e-6
With decimal arithmetic the toy book (bid 100.00, ask 100.02) has mid 100.01 and half-spread 0.01, which is 10000/10001 bp ≈ 0.9999 bp. Float64 lands on the same figure well inside 1e-6. That checks the formula. It is not a print from a symbol.
Rust holds the switch that keeps the desk on paper. Paste this into a crate you own; it is a sketch, not a published library.
pub struct RiskLimits {
pub paper_only: bool,
pub max_open_orders: u32,
pub max_order_notional: f64,
pub session_loss_stop_bps: f64,
}
pub fn allow_submit(limits: &RiskLimits, open_orders: u32, notional: f64) -> Result<(), &'static str> {
if !limits.paper_only {
return Err("paper_only is still required");
}
if open_orders >= limits.max_open_orders {
return Err("open-order cap");
}
if !(notional.is_finite() && notional > 0.0 && notional <= limits.max_order_notional) {
return Err("notional cap");
}
Ok(())
}
pub fn allow_session(limits: &RiskLimits, session_pnl_bps: f64) -> Result<(), &'static str> {
if session_pnl_bps <= -limits.session_loss_stop_bps {
return Err("session loss stop");
}
Ok(())
}
An illustrative blank, not a recommendation of outcomes: paper_only: true, max_open_orders: 1, max_order_notional left as a number you choose in account currency, session_loss_stop_bps: 50.0. Fifty basis points here means the paper session halts if marked paper PnL is at or below −50 bp. It is a switch. It is not an expected loss and not an expected gain.
Cross-check: the Rust cost function, when you add it, must return −9 and 26 on calculator A and B. If Python and Rust disagree, the desk stops. Do not average them.
Writer contract you can paste above the model prompt:
You draft code from the Evidence bundle only.
One hypothesis id. One falsifiable sentence. Unknowns stay listed.
Python tests first. Rust risk gate stays paper_only.
No API keys, no live flag, no holdout tuning, no invented fills.
If the authorization line is missing, refuse the task.
Background on agent + MCP framing: /blog/agent-reverse-engineering-mcp/. A full Codex install walkthrough, on a tiny public game rather than a market, is /docs/install-demo/.
5. Backtesting method: fees, slippage, time
A backtest on this desk is a procedure with a frozen snapshot. It is not a number we publish, because we did not run one for this article. Copy the procedure into the log and fill it with your data.
Snapshot. One directory, one SHA-256, one symbol list, one timezone. Features at time *t* may use rows with timestamp ≤ *t* only. Shuffling bars leaks the future. Choosing today's index members for a five-year study is survivorship unless the membership rule has an as-of date — record that rule or mark the bias.
Session-count template (calendar, not a sample of trades). US cash equities have about 252 sessions in a typical year. A walk-forward window this desk accepts as a default template is 252 sessions to fit and 63 sessions to test (252 / 4 = 63), rolled forward by 63. If your market does not use that calendar, write the real session count and keep the ratio explicit. Crypto that trades every day should say 365 (or 366) and pick a test window in days, not pretend it has 252 exchange holidays.
Three-way chronological split when you are not walking forward:
| Slice | Share of the timeline | Allowed use |
|---|---|---|
| Develop | First 70% | Invent and edit the hypothesis |
| Select | Next 15% | Choose among hypotheses already written down |
| Holdout | Last 15% | Touch once, then freeze the write-up |
The select slice is spent once K hypotheses have looked at it. Record K. Reusing select to crown a winner without a fresh later holdout empties the gate. The holdout is not a second develop set.
Fee grid. Run the identical fills through four round-trip fee assumptions. Report all four or report none.
| Column | Round-trip C_f | Role |
|---|---|---|
| Gross-only | 0 bp | Shows drag. Never a deployment column |
| Tight | 1 bp | Planning band for a schedule you have read and found near here |
| Default planning | 5 bp | Use while the CSV is not loaded yet |
| Harsh / two retail taker fills | 20 bp | 10 bp + 10 bp, i.e. 0.10% per side. Replace with your PDF when you have it |
If the sign of R_net flips between the 1 bp column and the 20 bp column, the log says cost-sensitive and the candidate stays off any live flag. That is a rule about columns, not a claim that your sign does or does not flip.
Slippage. Pick the decision price before you see the fill (mid at signal time, or last trade — one choice per experiment). When you have quotes, charge at least the half-spread in bp:
half_spread_bps = ((ask - bid) / 2) / mid * 10000
Then add a stress: half-spread alone, half-spread + 1 bp, half-spread + 5 bp. If you have no quotes, you have no slippage measurement — write C_s = unknown and do not substitute a flattering zero. The toy 100.00 / 100.02 book above is the unit test for the formula, about 0.9999 bp, not a symbol's spread.
Pass gates (method). Fail the candidate when any row is true:
| Gate | Fail when |
|---|---|
| Costs | Only gross is shown, or a single unstated fee |
| Chronology | Bars were shuffled, or a feature read a later row |
| Holdout | The last slice chose the parameters |
| Sample | Holdout round trips are under 30 |
| Sensitivity | You want a live flag while the fee columns disagree in sign |
| Evidence | An unknown from stage 2 was filled with a guess |
| Keys | A trade or withdraw credential is visible to the agent |
Under 30 holdout round trips is this page's desk rule: store the count, label the test underpowered, and do not quote a hit rate, profit factor, or Sharpe from it. Thirty is a small-sample warning we adopt so a short paper session cannot masquerade as confirmation. It is not a theorem that 30 trades prove a rule.
Numbers this page will not print: Sharpe, CAGR, win rate, profit factor, dollar PnL, "beats the market", or any filled equity curve. If you compute those later, they belong in your private log next to K, the fee grid, and the snapshot hash — and only after the gates above pass.
6. Autonomous research loop, with a human at the live switch
Autonomy here means the desk can repeat a logged procedure and investigate failures. It does not mean an unattended process with a trade key. The live flag stays absent from the tree until a named person has read the row.
- Append the experiment row before the run (the hypothesis sentence is pre-registered).
- Run on the frozen snapshot only.
- If a gate fails, write the failure class and stop editing that id against the holdout.
- If the gates pass, a paper session may start with the Rust limits loaded.
- The monitor calls
allow_sessionon marked paper PnL. A stop ends the session and writes the row. - A human reads the log before any later change to
paper_only.
Failure classes (use these words so the log stays searchable): lookahead, missing_cost, underpowered, implementation_drift, risk_limit, evidence_gap, cost_sensitive.
Row schema:
| Field | What you write |
|---|---|
experiment_id | Date plus counter, e.g. 2026-10-13-004 |
authorization | One sentence and a path |
artifact_sha256 | Hash from stage 2 |
rea_pin | [email protected] or the pin you actually ran |
model_id | Vendor id string, or none if you typed the code |
hypothesis | One falsifiable sentence |
snapshot_sha256 | Data directory hash and the date range |
fee_grid_bp | The four round-trip columns, or not_run |
slippage | half-spread+1bp or unknown |
split | 70/15/15 or 252/63 walk-forward |
K | How many hypotheses touched select |
holdout_round_trips | Integer count, even when small |
decision | reject, paper, or needs_data |
failure_class | From the list, or blank |
unknowns | Still open after the run |
Blank row you can imitate (this is a form, not an outcome): id 2026-10-13-004, decision needs_data, failure class evidence_gap, holdout round trips blank, unknowns "timestamp source not shown in on_bbo". No gross, no net, no Sharpe.
Risk limits you set in writing before the paper session:
| Control | Illustrative blank | Enforced by |
|---|---|---|
| Paper only | true | allow_submit returns an error otherwise |
| Max open orders | 1 | Same function |
| Max order notional | A number you choose | Same function; do not copy a dollar target from a chat |
| Session loss stop | 50 bp of paper notional | allow_session |
| Kill switch | A human command that sets paper sessions to stopped | Runbook, not the model |
| Live capital | No flag in the repo | Code review |
Weekly review, six ticks:
- Every new id has a pre-registered sentence.
doctor --jsonfrom the pin is still in the folder.- Python and Rust still agree on calculator A (−9) and B (26).
- No trade key appeared in the agent environment.
- Rejected ids were not silently renamed and rerun on the same holdout.
- Unknowns from REA are either closed with a location or still labeled unknown.
Operator FAQ
| Question | Answer |
|---|---|
| Can REA inspect any trading system? | It can inspect artifacts you are allowed to open. Venue binaries, broker apps, and other people's terminals need permission you actually have. |
| Does this page include a working strategy? | It includes a cost identity, a fee grid, a split, and a risk gate. It does not include a strategy result. |
| Which language does the agent write? | Python for the hypothesis and tests. Rust for the paper-only risk shell and the log. The model drafts; you merge. |
| Do I need Ghidra? | Only when the authorized artifact is a binary. It is bring-your-own. Source you wrote does not require it. |
| What is a good first target? | Your own paper gateway, or an open-source engine whose license you have read. |
| Where do I install REA? | /docs/install/ and the short loop on /docs/install-demo/. |
| Where are community cases? | /showcase/, especially /showcase/rea-investigate/. |
On rea.run
| Topic | Page |
|---|---|
| Install | /docs/install/ |
| Codex walkthrough | /docs/install-demo/ |
| MCP clients | /docs/mcp-clients/ |
| Showcase | /showcase/ |
| Investigation skill | /showcase/rea-investigate/ |
| Lab pin example | /showcase/rea-lab/ |
| 6.4.0 pin and compact schema | /blog/rea-agents-6-4-0/ |
| Agent + MCP | /blog/agent-reverse-engineering-mcp/ |
| Evidence over hype | /blog/evaluating-rea-claims/ |
| Security posture | /blog/rea-agent-security-posture/ |
| Legal boundary | /faq/legal-boundary/ |
| Compliance | /compliance/ |
Desk rules we keep
Authorized artifacts only. Evidence cites a location or an unknown. Costs use your schedule and the grid (0, 1, 5, and 20 bp round trip as the planning columns). Time stays in order. Under 30 holdout round trips, store the count and stop. paper_only stays true until a named human changes reviewed code. The research loop may reject candidates all week; that is the desk working.