rea.run

2026-10-13

Study trading software you are allowed to inspect

Research-desk diagram: an authorized target, REA and MCP inspection, an independent model, validation with costs and holdouts, then a pass gate into paper trading and an audit log.
Figure for this research desk. Read the flow as a gate: an authorized target, REA evidence, your own model, cost-aware validation, then paper trading under a risk limit you wrote down first. Headline wording printed on the picture is broader than this page. Work on software you own, open-source code the license lets you read, or a system covered by written permission.

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 figureDesk meaningYou may proceed when
Authorized targetPublic behavior of a program you may inspect, or an artifact you controlThe authorization note is in the experiment folder
REA + MCPInspect, trace, collect EvidenceFindings cite a path, symbol, or trace id, and unknowns are labeled
Independent modelYour code, not a paste of someone else's strategy textA unit test encodes the rule without a live account
Quant validationCosts, chronology, holdoutThe fee grid and the time split below are filled in
Pass / rejectFail closedA failed row names the gate; it does not get retuned on the holdout
Paper tradingForward behavior on a simulator you controlpaper_only is still true
AuditEvery try, including rejectsThe 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
SymbolNameWhere the number comes from
R_gGross strategy resultYour mark-to-decision-price rule, before costs
C_fExplicit feesThe fee schedule of your account: commission, exchange, regulatory
C_sSlippageDistance from the decision price to the modeled fill
C_mSpread and impactAt least half the bid-ask when you cross; plus a stress you add
C_oOther operating costBorrow, funding, data, or anything you pay that is not in the three cells above
R_netNetArithmetic 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.

CellCalculator ACalculator B
R_g12 bp30 bp
C_f20 bp2 bp
C_s1 bp1 bp
C_m0 bp1 bp
C_o0 bp0 bp
R_net−9 bp26 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.

TargetOn this pageStop
Source you wroteMap functions and configKeep secrets out of the prompt log
Open-source strategy or engine code, license permits readingTrace and reimplement ideas in your own wordsRespect the license; do not republish large verbatim trees
Binary you compiled, or a vendor binary under a contract that allows inspectionHash it, then BYO a licensed decompilerDisposable VM if you did not build it
Employer or client system with written permissionStay inside the named paths and the retention ruleDo not copy Evidence out of that permission
Someone else's prop terminal, broker app, or venue binary without permissionOut of scope/faq/legal-boundary/
License cracks, DRM bypass, credential theft, live probing of a venueOut of scope/compliance/

Preflight, in order:

  1. Write one sentence of authorization: owner, path, date, and whether paper trading is allowed.
  2. Pin the tool: npx -y [email protected] (site teaching pin as of the 6.4.0 ops guide). Save doctor --json.
  3. Record SHA-256 of every artifact you open.
  4. 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.
  5. If the client caps MCP schema size, set REA_MCP_INPUT_SCHEMA_PROFILE=compact and reconnect. See /blog/rea-agents-6-4-0/ and /faq/mcp-schema-size/.
  6. 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.

#StageQuestionArtifact you keepFail closed when
1REA workflowWhat does this program do, and along which paths?Dependency map + Evidence idsThe answer has no location
2Source and binaryWhich functions implement that path?Path:line or address, plus unknownsThe prompt asks to bypass a license check
3BehaviorHow do submit, cancel, market data, and fills line up?Event table joined to stage 2The session sent a live order
4HypothesisWhat rule would explain the evidence, and how do we falsify it?Python test + optional Rust shellThe model invented a fill
5Backtest methodDoes the rule survive costs and a time split?Fee grid, slippage note, holdout countParameters were chosen on the holdout
6Research loopWhat failed, and which limit binds?Append-only log + risk structA 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:

  1. Where is an order message built (side, quantity, price, time in force)?
  2. Where is a cancel built, and which id joins it to the submit?
  3. Which handler consumes a market-data update, and which fields does it trust?
  4. Which local predicate can reject an order before it leaves the process?

Pass and fail look different:

AskPassFail
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 defaultA guessed commission
What updates the book?Handler name and field listA paragraph about how markets work
What rejects locally?The predicate and its locationThe 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".

  1. sha256sum the tree or the binary. Store the hash in the log before any conclusion.
  2. Source: request a module map (market data, order, risk, UI or CLI) with paths.
  3. 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.
  4. Keep the untrusted binary in a disposable VM. Process capture is not a sandbox (/blog/rea-agent-security-posture/).
  5. Every claim is either a location or an explicit unknown. Chat prose does not upgrade itself to Evidence (/blog/evaluating-rea-claims/).
  6. 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:

FieldExample shape (not a real program)
Artifactpaper-gateway @ SHA-256 recorded in the log
Order buildoms/build.rs function build_limit
Cancel joinClient id field cid, unsigned 64-bit
Market datamd/parse.rs handler on_bbo fields bid, ask, ts
Local rejectrisk/gate.rs returns err when qty == 0
UnknownWhether 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.

EventMinimum fieldsWhy you keep them
md_updatets_exchange, ts_local, symbol, bid, ask, lastDecision price and clock skew
order_submitclient id, side, qty, limit, time in force, ts_localThe intent
order_ackclient id, venue or sim id, statusThe join key
order_cancelclient id, reasonLifecycle, not a guess
execprice, qty, liquidity flag if the sim has oneThe fill you will charge costs against
rejectcode, text, which predicate firedDistinguishes 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.

PieceWhoOwnsDoes not own
ObservationREA MCPEvidence, paths, unknownsA story about profit
WriterOpus-class model, pinned model idA hypothesis sentence and a diffOrder keys, the holdout, permission
HypothesisPythonThe rule, the cost identity, deterministic testsLive I/O
Risk shellRustpaper_only, caps, append-only logA decompiler or a venue exploit
HumanYouAuthorization, the fee CSV, reading the diffBlind 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:

SliceShare of the timelineAllowed use
DevelopFirst 70%Invent and edit the hypothesis
SelectNext 15%Choose among hypotheses already written down
HoldoutLast 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.

ColumnRound-trip C_fRole
Gross-only0 bpShows drag. Never a deployment column
Tight1 bpPlanning band for a schedule you have read and found near here
Default planning5 bpUse while the CSV is not loaded yet
Harsh / two retail taker fills20 bp10 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:

GateFail when
CostsOnly gross is shown, or a single unstated fee
ChronologyBars were shuffled, or a feature read a later row
HoldoutThe last slice chose the parameters
SampleHoldout round trips are under 30
SensitivityYou want a live flag while the fee columns disagree in sign
EvidenceAn unknown from stage 2 was filled with a guess
KeysA 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.

  1. Append the experiment row before the run (the hypothesis sentence is pre-registered).
  2. Run on the frozen snapshot only.
  3. If a gate fails, write the failure class and stop editing that id against the holdout.
  4. If the gates pass, a paper session may start with the Rust limits loaded.
  5. The monitor calls allow_session on marked paper PnL. A stop ends the session and writes the row.
  6. 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:

FieldWhat you write
experiment_idDate plus counter, e.g. 2026-10-13-004
authorizationOne sentence and a path
artifact_sha256Hash from stage 2
rea_pin[email protected] or the pin you actually ran
model_idVendor id string, or none if you typed the code
hypothesisOne falsifiable sentence
snapshot_sha256Data directory hash and the date range
fee_grid_bpThe four round-trip columns, or not_run
slippagehalf-spread+1bp or unknown
split70/15/15 or 252/63 walk-forward
KHow many hypotheses touched select
holdout_round_tripsInteger count, even when small
decisionreject, paper, or needs_data
failure_classFrom the list, or blank
unknownsStill 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:

ControlIllustrative blankEnforced by
Paper onlytrueallow_submit returns an error otherwise
Max open orders1Same function
Max order notionalA number you chooseSame function; do not copy a dollar target from a chat
Session loss stop50 bp of paper notionalallow_session
Kill switchA human command that sets paper sessions to stoppedRunbook, not the model
Live capitalNo flag in the repoCode review

Weekly review, six ticks:

  1. Every new id has a pre-registered sentence.
  2. doctor --json from the pin is still in the folder.
  3. Python and Rust still agree on calculator A (−9) and B (26).
  4. No trade key appeared in the agent environment.
  5. Rejected ids were not silently renamed and rerun on the same holdout.
  6. Unknowns from REA are either closed with a location or still labeled unknown.

Operator FAQ

QuestionAnswer
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

TopicPage
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.