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.
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.
DECISION_CONTRACT prepended to turn wakeups.t3-trade.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.
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.
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.
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. |
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.
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.
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.
positivePnlExpandsLossBudget = false. Trading profits reduce realizedLossUsedUsd toward $0$, but never expand maximumCumulativeLossUsd beyond the user's hard mandate ceiling.
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.
To achieve total idempotency across network disconnects and node restarts, client order IDs are derived deterministically using SHA-256:
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.
When trading_adjust_stop is called, TradingStopAdjustmentService evaluates 7 mathematical safety invariants before issuing a place-and-confirm replacement:
observedAtrUsd is cross-checked against the server's rolling 14-bar ATR: $|\text{observedAtr} - \text{serverAtr}| / \text{serverAtr} \le 30\%$.
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.