Deterministic Autonomous Architecture

The 24 Injected Tools of T3 Trade

T3 Trade injects 24 typed tools into AI agent harnesses (Claude Code, OpenAI Codex, Cursor, Grok, OpenCode). The tools serve as a clean, deterministic abstraction layer—completely shielding the AI agent from raw database queries, exchange API signatures, nonce coordination, and low-level state reconciliation.

24
Injected Tools
7
Turn Gate Checks
17
Pre-Execution Checks
0
Upstream Complexity

The Tool Layer as the Pure Abstraction Barrier

Upstream complexities are abstracted away behind the 24 tools. The harness only ever interacts with typed Effect schemas, while the tool handlers enforce authorization, session leases, mathematical safety gates, and atomic exchange state synchronization.

🤖
AI Agent Harnesses
Strategy & Decision Making
Claude Code / Anthropic
Runs under strict tool lock (no filesystem/terminal access in trading sessions).
Codex & Cursor
Receives DECISION_CONTRACT prepended to turn wakeups.
Grok & OpenCode
Connects via standard first-party MCP endpoint t3-trade.
T3 Trade Tools Layer
The 24 Typed Effect Boundaries
Strategy & Mission (3)
Mandate ceilings, verified target basis, and deterministic playbooks.
Market Intelligence (7)
Multi-TF trend scores, ATR volatility, L2 depth, and round-trip cost gates.
Account & Calibration (5)
Flat-to-flat trade history, target accuracy grading, and peak uPnL memory.
Reactive Watches (3)
Exact-once triggers (price, candle close, PnL giveback) for sleeping agents.
Execution & Exits (6)
Pre-checked quotes, single-token execution, anti-dust exits, and dynamic stops.
🛡️
Abstracted Upstream Core
Hidden from the AI Harness
17-Point Preview Engine
Eq-4 risk reservation ledger and cumulative loss accounting.
Nonce Lane & EIP-712
Single permit serial signing and deterministic cloid generation.
Hyperliquid L1 Reconciler
2-second state synchronization and fill deduplication.

What Happens Between the Harness and the Tools

Select an interactive trading lifecycle flow below to trace the exact request, internal abstraction, and typed response exchanged between the AI harness and the T3 Trade tool layer.

1. Tournament & Precision Entry

The harness wakes, reads multi-timeframe structure, runs a strategy tournament against cost gates, publishes an audited plan, requests a server-clamped quote, and executes atomically.

Step A: What the Harness Sends Harness Intent
The harness supplies its analysis arguments to the tool.
{ "market": "ETH" }
Step B: What the Tool Does (Abstracted Away) Tool Abstraction
The tool validates capability, queries live L2 order book, and executes calculation.
Step C: What is Returned to the Harness Typed Response
Clean, structured output returned to the AI context.
{ "status": "ok" }

All 24 T3 Trade Tools Explained

Every tool is defined in @t3tools/trading-contracts and implemented in apps/server/src/mcp/toolkits/trading. Explore their surface purpose, internal abstraction logic, and exact interfaces.

Technical Deep Dive & System Invariants

Exhaustive specification of the mathematical models, concurrency control, turn coordination gates, place-and-confirm execution pipeline, and state reconciliation invariants implemented in T3 Trade.

🔄 §12.3 TradingTurnCoordinator & The 7 Pre-Run Gates

TradingTurnCoordinator acts as the strict serial gateway between an observed market/watch event and a started harness run. To guarantee zero concurrent runs on the same mission, the coordinator runs 7 ordered checks before acquiring the decision lease in SQLite:

# Pre-Run Check Implementation Invariant Outcome if Blocked
1 Mission Active isActiveMissionStatus(mission.status): Must be in operative status (not terminated/revoked). blocked: mission_not_active
2 Provider Binding Present mission.harness.threadId must be non-empty and bound to an operative thread. blocked: provider_binding_missing
3 Provider Available mission.harness.status !== "unavailable". blocked: provider_unavailable
4 Single-Lease Acquisition Atomic INSERT INTO trading_harness_runs with partial unique index idx_trading_harness_runs_one_active_per_mission. queued_behind_active_run (Gracefully drops duplicate wakes)
5 Account Ready Trading master wallet and account state record resolved. blocked: account_unavailable
6 Claim Pending Inbox Events TradingEventInbox.claimPending: Atomic flip to included_in_run prevents stale duplicate wakeups. Events claimed into wakeup payload
7 Strategy & Authority Versions Loads current strategy and authority. Non-strategy runs only permitted for bootstrap / scheduled reassessment / user messages. blocked: no_active_strategy

Watcher Fiber Lifecycle: Upon successful lease acquisition, a detached fiber runs watchTurnEndAndRelease, streaming domain events and waiting for the first thread.session-set event where the session leaves "running" without an active turn (matching statuses: idle, ready, interrupted, stopped, error). When detected, the fiber closes telemetry with settleRunDecision, marks claimed inbox events consumed, releases the SQLite lease, and calls ensureNotDeaf to automatically arm staleness coverage floors.

🛡️ §16.3 The 17-Point Pre-Execution Risk Invariant Checklist

Before any position-increasing intent is signed, TradingPreviewService.previewOrder executes 17 distinct invariant checks in listed, load-bearing order. This service is a pure, side-effect-free evaluator over reconciled truth.

# Invariant Tag Evaluation Logic & Failure Conditions
1 mission_active ctx.mission.status === "executing" || "position_open". Rejects paused or terminated missions.
2 entries_allowed ctx.mission.control.entriesAllowed && !mission.status.includes("blocked").
3 strategy_version_current intent.strategyVersion === ctx.currentStrategyVersion (Optimistic versioning lock).
4 authority_version_current ctx.expectedAuthorityVersion === ctx.currentAuthorityVersion (Prevents stale risk ceilings).
5 harness_run_owns_lease ctx.activeHarnessRunId === ctx.requestingHarnessRunId. Rejects actions from expired turns.
6 direction_permitted Validates allowedDirections ('long'/'short'), allowDirectionReversal, and allowScaleIn.
7 market_is_eth intent.market === ctx.mission.market (Enforces single-asset mandate).
8 execution_wallet_approved ctx.approvedExecutionWalletAddress !== null (Interim signer armed address resolution).
9 account_and_bbo_fresh BBO age $\le 2000\text{ms}$; Account snapshot age $\le 5000\text{ms}$. Rejects stale market data.
10 size_and_price_valid intent.size > 0 && intent.limitPrice > 0.
11 exchange_minimum_met $\text{notional} = \text{size} \times \text{limitPrice} \ge \$10.00$ Hyperliquid protocol minimum.
12 leverage_within_limits $(\text{existingNotional} + \text{proposedNotional}) / \text{allocatedCapital} \le \text{maximumLeverage}$.
13 gross_notional_within_authority $\text{existingNotional} + \text{proposedNotional} \le \text{maximumGrossNotionalUsd}$.
14 planned_loss_within_per_position_ceiling $\text{plannedLossAtStop} \le \text{maximumPlannedRiskPerPositionUsd}$.
15 reservations_plus_proposed_within_budget Evaluates Eq-4 ledger: $\text{proposedReservation} \le \text{remainingCumulativeLossBudget}$.
16 no_conflicting_execution_pending Ensures no prior execution record is in flight in submitted or pending state.
17 valid_stop_defined checkStopInformation verifies mandatory stop presence, side correctness, and noise floor.
📐 §16.2 Cumulative Loss Budgeting & The Six Risk Equations

T3 Trade enforces a deterministic, closed-form loss accounting system where worst-case stop-out loss, exchange taker fees, and slippage buffers are reserved before any cryptographic signature is produced.

Eq 1: realizedMissionResultUsd = closedPnlUsd + netFundingUsd - allPaidTradingFeesUsd
Eq 2: realizedLossUsedUsd = max(0, -realizedMissionResultUsd)
Eq 3: openPositionRiskUsd = max(0, estimatedLossFromWeightedEntryToStopUsd) + unpaidExitFeeUsd + stopSlippageReserveUsd
Eq 4: pendingEntryRiskUsd = plannedLossAtStopUsd + estimatedEntryFeeUsd + estimatedExitFeeUsd + stopSlippageReserveUsd
Eq 5: lossBudgetUsedUsd = realizedLossUsedUsd + Σ(openPositionRiskUsd) + Σ(pendingEntryRiskUsd)
Eq 6: remainingCumulativeLossUsd = max(0, maximumCumulativeLossUsd - lossBudgetUsedUsd)
Missing Stop Semantics (Eq 3)
When stopPrice is undefined on an open position, directional loss contributes $0$ (unknown, not zero-priced). A missing stop is never substituted with $0$, which would book the entire position notional as risk and exhaust capital immediately.
Anti Double-Counting of Fees
Paid entry fees reside inside realizedMissionResultUsd; they are never double-counted as unpaid open position risk. A queued entry reserves both entry and exit fees; a filled position reserves only the unpaid exit fee.
Asymmetric Profit Expansion
positivePnlExpandsLossBudget = false. Trading profits reduce realizedLossUsedUsd toward $0$, but never expand maximumCumulativeLossUsd beyond the user's hard mandate ceiling.
Exhaustion Lock (§16.4)
When remainingCumulativeLossUsd <= 0, all position-increasing orders are blocked, mission transitions to blocked: cumulative_loss_limit, and only reduce-only closing orders and stop improvements are accepted.
🔑 Deterministic Client Order ID (Cloid) & Nonce Permits

To achieve total idempotency across network disconnects and node restarts, client order IDs are derived deterministically using SHA-256:

cloid = hex(SHA-256(missionId ‖ strategyVersion ‖ executionSequence ‖ actionType)[0..15])

Single-Permit Nonce Lane: All signed exchange actions (orders, cancellations) pass through HyperliquidNonceCoordinator. The coordinator maintains a serialized FIFO permit lane to guarantee strictly monotonic nonces without racing. If an out-of-order nonce error is detected from the L1 gateway, the coordinator automatically fast-forwards the monotonic nonce baseline to exchangeTimestamp + 1.

🛡️ Dynamic Stop Policy & The 7 Mathematical Invariants

When trading_adjust_stop is called, TradingStopAdjustmentService evaluates 7 mathematical safety invariants before issuing a place-and-confirm replacement:

1. Breakeven Ratchet
If the current resting stop has already crossed the entry price into profit territory, any new stop must satisfy $\text{newStop} \ge \text{entryPrice}$ (for longs) or $\text{newStop} \le \text{entryPrice}$ (for shorts). A winning trade cannot regress into risk.
2. Max Step Constraint
Adjustment step is bounded: $|\text{newStop} - \text{currentStop}| \le \min(0.5 \times \text{ATR}, 0.25 \times \text{currentStopDistance})$. Prevents jarring leaps that risk immediate wick-outs.
3. Noise Floor Minimum
Stop distance to mark must clear market microstructure noise: $|\text{mark} - \text{newStop}| \ge \max(2 \times \text{halfSpread}, 0.35 \times \text{ATR})$.
4. Server ATR Cross-Validation
The harness's submitted observedAtrUsd is cross-checked against the server's rolling 14-bar ATR: $|\text{observedAtr} - \text{serverAtr}| / \text{serverAtr} \le 30\%$.
5. Target Encroachment Guard
The stop cannot encroach closer than $50\%$ of the entry-to-profit-target corridor, preventing premature profit clipping.
6. Rate Limiting & Budget
Maximum 8 adjustments per position lifetime. Rate-limited to at most 1 adjustment per 3 primary timeframe bars.
⏱️ Reactive Watch Evaluator & Automatic Deaf-Prevention Floors

WatchEvaluator provides an event-driven wakeup engine for sleeping harnesses:

Dual Stream Architecture: Subscribes to Hyperliquid L1 WebSocket candle feeds (1m, 3m, 5m, 15m, 1h) and executes a 2-second periodic sweep for price_cross and scheduled_reassessment triggers.
Atomic State Transition: Firing flips watch status from active → triggered in SQLite and writes an inbox deduplication key (type:watchId:...).
Deaf-Prevention Coverage Floor: When a turn completes, ensureNotDeaf evaluates whether the position is protected on both sides. If no watch is armed, the system automatically registers a scheduled_reassessment staleness floor, preventing silent abandonment.