TradeMemory Protocol
TradeMemory Protocol is a local-first, memory-and-brake server that lets an AI trading agent record trades, recall its own past outcomes before the next order, gate trades on risk/behavioral checks, and keep a tamper-evident audit trail.
Record trades —
remember_tradestores fills into five memory layers (episodic, semantic, procedural, affective, trade records), with P&L, R-multiple, context, regime, ATR, excursions, and reflections.Recall memories —
recall_memoriesreturns ranked past trades using OWM outcome-weighted scoring (with optional hybrid vector blending) so losing trades surface before a new order.Review performance —
get_strategy_performanceandget_trade_reflectiongive per-strategy aggregate stats and deep dives into individual trades.Read agent state —
get_agent_statereports confidence, drawdown, streaks, and a recommended action;get_behavioral_analysisflags hold times, disposition ratio, sizing variance, and Kelly comparison.Plan ahead —
create_trading_planandcheck_active_plansstore and match conditional, expiring prospective plans.Gate trades —
check_trade_legitimacy(sample size, regime experience, streak, drawdown) andcompute_dqsscore the decision process;validate_strategyruns DSR, walk-forward, regime, and CPCV tests on a CSV trade log.Discover/evolve strategies —
evolution_fetch_market_data,evolution_discover_patterns,evolution_run_backtest,evolution_evolve_strategy, andevolution_get_logfetch Binance OHLCV, generate LLM patterns, backtest them, and run multi-generation evolution.Audit decisions —
export_audit_trail,verify_audit_hash,verify_audit_chain, andget_daily_rootprovide SHA-256 chained Trading Decision Records with daily Merkle roots and optional RFC 3161 timestamps.
Note: this tool set is the read/record/analysis memory server — it never places orders or holds broker keys; order braking and policy enforcement come from the separate proxy extra (Mnemox Control) and Alpaca sync is a CLI step, not one of these 20 tools.
Synchronizes trading data from Binance into the memory protocol to provide AI agents with historical context and outcome-weighted insights for improved trade decision-making.
Enables users to interact with the trading memory protocol through WhatsApp via an OpenClaw agent, allowing for remote trade journaling and performance analysis.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@TradeMemory Protocol analyze my recent trades to identify patterns and behavioral biases"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Getting Started | Use Cases | API Reference | OWM Framework | Limitations | 中文版
TradeMemory remembers what it cost. It is an open-source, local-first memory and brake for AI trading agents: it pulls in your fills, finds where your own history loses money, puts those losing trades in front of your agent before the next order, and can refuse an order that breaks rules you set, before it reaches the broker.
Brokers now let AI agents trade over MCP, with different guardrails: Webull and tastytrade set size or buying-power limits, Interactive Brokers only lets the agent draft an order for you to submit, and Robinhood and Public set no cap you can impose on an external agent (StockBrokers, 2026-09-30). The caps are fixed numbers. None of them looks at how your own past trades went.
Start with your own history
pip install tradememory-protocol
# Hyperliquid: public fills, no key needed
tradememory sync hyperliquid --address 0xYourAddress
# Alpaca: read-only calls with your own keys, kept in a local file
tradememory sync alpaca --env-file ~/.secrets/alpaca.envEach closed trade is stored in memory once; running it again stores only new trades. Then it prints where your history loses money. The format, with illustrative numbers:
After 2 losses in a row (20 trades):
5 of them (25%) were 1.5x your usual size or more.
All 20 won 60% and made -$1,500.
The 5 sized-up trades won 20% and made -$1,700.
Median hold: winners 1.5h, losers 9.0h.These are descriptive statistics of your own past trades, not advice about the next one. Hyperliquid's API serves only an address's recent fills, not its whole history, so the sooner it is synced, the more history is kept. Other venues: MT5 and Binance spot sync scripts are in scripts/, and any agent can record a trade with remember_trade.
Related MCP server: AgentRecall
Before the next order
recall_memories(order="losses_first") puts every losing trade ahead of the rest, the bigger losses in similar conditions first, with their size and P&L. Besides the symbol's most recent trades, it searches the symbol's recent losing trades, so an older loss is not crowded out. The server tells connected agents to call it before proposing a trade. The default order ranks better outcomes higher (by R multiple, where one was recorded) and keeps at least 20% losses in the list.
Connect your agent
pip install tradememory-protocolAdd to Claude Desktop (claude_desktop_config.json):
{
"mcpServers": {
"tradememory": {
"command": "uvx",
"args": ["tradememory-protocol"]
}
}
}Then tell Claude: "Record my AAPL long at $195 — earnings beat, institutional buying, high confidence."
# Claude Code
claude mcp add tradememory -- uvx tradememory-protocol
# From source
git clone https://github.com/mnemox-ai/tradememory-protocol.git
cd tradememory-protocol && pip install -e . && python -m tradememory
# Docker
docker compose up -dFull walkthrough: Getting Started (Trader Track + Developer Track)
Put a brake in front of your broker (preview)
The proxy extra runs TradeMemory between your agent and your broker's MCP server (Alpaca today). Every tool is forwarded unchanged except the order-placing ones, which Mnemox Control evaluates against a policy you own before they reach the broker. Every evaluation, allowed or refused, is recorded and chained into the audit log. An allowed order comes back with your losing trades from similar conditions first, and tradememory sync alpaca later fills in how each forwarded trade ended, in R when the entry carried a stop. The agent you already have keeps working; only one line of its MCP config changes.
pip install "tradememory-protocol[proxy]" # Python 3.12+
tradememory proxy init --account-id <your Alpaca account id> --symbols AAPL,MSFT
tradememory proxy doctor --env-file ~/.secrets/alpaca-paper.env # checks the live tool names and the account id
tradememory proxy config # prints the MCP client entry that replaces the direct Alpaca oneRefused by default: symbols outside your list, orders above your notional and position limits, entries without a bracket stop, any new order after your daily-loss or drawdown limit, cancelling the protective stop of an open position, any tool the brake has not classified, and everything while you have run tradememory proxy halt FULL_HALT. Never blocked: closing a position. Orders at or above approval_notional wait for tradememory proxy approve <intent_id> --terms <fingerprint>, which approves exactly the terms you read; the agent retries with the same client_order_id and the same terms, and the proxy forwards it at most once. evaluate_order returns the same decision without placing anything, for pre-checks and for advisory layers in other frameworks. Anything the brake cannot evaluate (a dead quote feed, an unknown asset, an order type the policy does not cover) is refused, not passed through.
Status: tested end-to-end against a stateful fake of Alpaca's MCP server (tests/proxy/), and run against a real Alpaca paper account on 2026-10-01: three refusals (symbol not on the list, entry without a stop, notional over the limit), one allowed one-share bracket order that reached the broker, and one retry with the same client_order_id that was answered from the record without a second order. Options, order replacement, stop-limit and trailing orders are refused rather than evaluated. Your broker keys go only to the broker process the proxy starts; TradeMemory never stores them.
Walkthrough with the real outputs: docs/recipes/alpaca-brake.md.
Three ways it is used
US equity trader | Forex EA system | Audit trail (illustrative) | |
Market | Stocks (AAPL, TSLA, ...) | XAUUSD (Gold) | Multi-asset |
How | Pre-flight checklist before every trade | Automated sync from MT5 | Decision records with a hash chain |
Who | One independent user (March 2026) | The maintainer's own MT5 account | An example, not a customer |
Details |
How it works
Recall — Before trading, retrieve past trades weighted by outcome quality, context similarity, recency, confidence, and emotional state (OWM Framework)
Record — After trading, one call to
remember_tradewrites to five memory layers: episodic, semantic, procedural, affective, and trade recordsReflect — Daily/weekly/monthly reviews detect behavioral drift, strategy decay, and trading mistakes
Audit — Every decision is SHA-256 hashed at creation and chained to the one before. Export anytime for review
MCP Tools
Category | Tools | Description |
Memory |
| Record and recall trades with outcome-weighted scoring |
State |
| Confidence, drawdown, streaks, behavioral patterns |
Planning |
| Prospective plans with conditional triggers |
Risk |
| 5-factor pre-trade gate (full / reduced / skip) |
Audit |
| SHA-256 tamper detection + bulk export |
Category | Tools |
Core Memory |
|
OWM Cognitive |
|
Risk & Governance |
|
Evolution |
|
Audit |
|
REST API: 35+ endpoints for trade recording, reflections, risk, MT5 sync, OWM, evolution, and audit. Full reference →
Get help connecting
Running an agent against a broker, or want your history synced and read? Open a brake-integration issue or book 30 minutes. Setup help is free, and the people who use it decide what gets built next.
Audit trail
Every trading decision your agent makes — including decisions not to trade — is recorded as a Trading Decision Record (TDR). Per-record SHA-256 content hashes are linked into a forward-chained audit ledger; every UTC day is summarised by a Merkle root which itself chains across days. Tampering with any historical record invalidates every subsequent link.
Rules that require decision records bind investment firms, not retail users. Under the EU AI Act, the Annex III high-risk logging obligations were postponed to 2 December 2027, and ESMA's February 2026 supervisory briefing on algorithmic trading states that AI-based algorithmic trading is currently excluded from the high-risk scope. The table shows which TradeMemory features map to those texts if and when they apply to you. It is not a compliance claim.
Regulation | Requirement | TradeMemory Coverage |
MiFID II Article 17 | Record every algorithmic trading decision factor | Full decision chain: conditions, filters, indicators, execution |
EU AI Act Article 14 | Human oversight of high-risk AI systems | Explainable reasoning + memory context for every decision |
EU AI Act Article 12 | Automatic, tamper-resistant logs over system lifetime | Linked SHA-256 chain + daily Merkle roots (RFC 3161 TSA anchoring, on by default since 0.5.3) |
# Verify a single record hasn't been tampered with
verify_audit_hash(trade_id="MT5-7047640363")
# → {"verified": true, "chain_entry": {"sequence_num": 42, ...}}
# Walk the entire chain (or a slice) end-to-end
verify_audit_chain(from_seq=1, to_seq=None)
# → {"verified": true, "checked_count": 1284, "first_break_at": null}
# Daily Merkle root — single 32-byte anchor over every TDR for that day
get_daily_root(date="2026-05-14")
# → {"verified": true, "root_hash": "a05544...", "record_count": 18}
# Bulk export
GET /audit/export?strategy=VolBreakout&start=2026-03-01&format=jsonlDaily roots are timestamped by an RFC 3161 authority by default since 0.5.3. Not built: signing records with a private key, anchoring to a public log, proving that nothing was left out. See LIMITATIONS.md.
Security
Memory server (default). Never places orders and never asks for broker keys. Records and recalls only, in a local SQLite file.
Sync.
tradememory sync hyperliquidreads public data with no key.tradememory sync alpacamakes read-only calls with keys from a file on your machine. Synced trades stay in your local database.Brake (
proxyextra). Forwards the orders your policy allows to your broker's MCP server. Your broker keys are passed only to the broker process the proxy starts; TradeMemory never stores them.Outbound calls. RFC 3161 timestamping of daily audit roots, a 32-byte hash with no trade data (on by default;
TRADEMEMORY_TSA=offturns it off).tradememory synccalls the venue you name. The evolution tools read public Binance market data (api.binance.com) when an agent calls them, and evolution calls the Anthropic API only if you setANTHROPIC_API_KEY. Replay calls DeepSeek by default (or Anthropic), and only with that provider's key set. If you installsentence-transformersfor hybrid recall, it downloads its model from Hugging Face on first use. The MT5 and Binance sync scripts inscripts/read their credentials from your environment, and the MT5 one posts trade summaries (symbol, prices, P&L) to a Discord webhook only if you setDISCORD_WEBHOOK_URL.Tamper-evident, not tamper-proof. Every record is hashed and linked to the one before, with daily Merkle roots. Changing a record breaks the chain; someone who can rewrite the whole database can rebuild it.
Research Status
TradeMemory's OWM framework is grounded in cognitive science (Tulving 1972) and reinforcement learning (Schaul et al. 2015). Current status:
OWM five-factor scoring: implemented and tested (see the CI badge)
Statistical validation: DSR, MBL implemented (Bailey-de Prado 2014)
Audit trail: SHA-256 tamper-evident TDR
Evolution engine: research phase (strategy generation works, statistical gate pass rate under optimization)
Hybrid recall: OWM-only mode active, vector fusion available when embeddings configured
Empirical validation: ongoing (n=14 trades, target n>=100 for statistical significance; at n=14 the confidence intervals are too wide to conclude anything - see validation/final_verdict.md)
Documentation
Doc | Description |
Install → first trade → pre-flight checklist | |
3 usage scenarios, each labelled first-party or independent | |
All REST endpoints | |
Outcome-Weighted Memory theory | |
System design & layer separation | |
Detailed walkthrough | |
MetaTrader 5 integration | |
Evolution experiments & data | |
11 trading AI failure modes | |
Traditional Chinese |
Contributing
See Contributing Guide · Security Policy
MIT, see LICENSE. The optional proxy extra installs Mnemox Control, whose engine is AGPL-3.0-only (a commercial license is available); TradeMemory itself stays MIT. For educational and research purposes only. Not financial advice.
Available Tools
20 toolscheck_active_plansAIdempotent
Check active trading plans against current market context.
Queries all active prospective plans, expires any past their expiry date, and matches remaining plans against the provided context.
Inputs: context_atr_d1, context_regime. Returns: object
check_trade_legitimacyAIdempotent
Check if the agent has sufficient data and confidence to trade.
Call this before making any trade decision. Evaluates sample size, memory quality, regime experience, streak state, and drawdown to determine whether the agent has earned the right to trade at full size.
Inputs: strategy_name (required), symbol, current_atr_d1, current_regime. Returns: object
compute_dqsAIdempotent
Compute Decision Quality Score before executing a trade.
Evaluates the quality of the decision process (not outcome) across 5 factors: regime match, position sizing vs Kelly, process adherence (OWM similarity), risk state, and historical pattern.
Inputs: symbol (required), direction (required), strategy_name (required), context_atr_d1, +3 more. Returns: object
create_trading_planA
Create a prospective trading plan that activates when conditions are met.
Stores a rule-based plan in prospective memory. The plan stays active until triggered, expired, or manually cancelled.
Inputs: reasoning (required), trigger_type (required), planned_action (required), trigger_condition (required), +2 more. Returns: object
evolution_discover_patternsA
Discover trading patterns from market data using LLM analysis.
Uses Claude to analyze OHLCV data and generate candidate trading patterns with entry/exit conditions. Each pattern can be backtested afterward.
Inputs: symbol (required), days, count, timeframe, +1 more. Returns: object
evolution_evolve_strategyA
Run full evolution loop — generate, backtest, select, eliminate.
Multi-generation strategy evolution: generates candidate patterns via LLM, backtests on in-sample data, validates survivors on out-of-sample data, eliminates weak hypotheses. Returns graduated strategies and graveyard.
Inputs: symbol (required), days, timeframe, generations, +1 more. Returns: object
evolution_fetch_market_dataAIdempotent
Fetch OHLCV market data from Binance for evolution analysis.
Downloads historical price bars for backtesting and pattern discovery. Use this before discover_patterns or run_backtest to get data.
Inputs: symbol (required), days, timeframe. Returns: object
evolution_get_logARead-onlyIdempotent
Get the log of past evolution runs from this session.
Returns a list of all evolution runs with their results, including graduated strategies, graveyard, token usage, and backtest counts. Data is in-memory (resets on server restart).
Inputs: no named parameters. Returns: object
evolution_run_backtestAIdempotent
Backtest a candidate pattern against historical OHLCV data.
Takes a pattern dict (from discover_patterns) and runs a vectorized backtest. Returns fitness metrics: Sharpe ratio, win rate, trade count, max drawdown, total PnL.
Inputs: pattern_dict (required), days, symbol, timeframe. Returns: object
export_audit_trailARead-onlyIdempotent
Export Trading Decision Records for audit and compliance review.
Provides a complete, tamper-evident record of trading decisions including the memory context (similar trades, beliefs) that informed each decision.
Inputs: end, limit, start, strategy, +1 more. Returns: object
get_agent_stateARead-onlyIdempotent
Get the current agent affective state (confidence, risk, drawdown).
Returns confidence level, risk appetite, drawdown percentage, win/loss streaks, equity tracking, and a recommended action based on current drawdown severity.
Inputs: no named parameters. Returns: object
get_behavioral_analysisARead-onlyIdempotent
Get behavioral analysis from procedural memory.
Returns aggregate trading behavior stats: hold times, disposition ratio, lot sizing variance, and Kelly criterion comparison.
Inputs: symbol, strategy_name. Returns: object
get_daily_rootAIdempotent
Get (or rebuild) the daily Merkle root for a UTC date.
The Merkle root summarises every audit_chain entry whose chained_at
falls inside the UTC day. Verifying this single 32-byte root proves
the integrity of every TDR for that day without re-walking each one.
Inputs: date (required), rebuild, request_tsa, include_token. Returns: object
get_strategy_performanceARead-onlyIdempotent
Get aggregate performance stats per strategy.
Use this to evaluate which strategies are working and which need adjustment.
Inputs: symbol, strategy_name. Returns: object
get_trade_reflectionARead-onlyIdempotent
Get the full context and reflection for a specific trade.
Use this to deep-dive into a particular trade's reasoning and lessons.
Inputs: trade_id (required). Returns: object
recall_memoriesAIdempotent
Recall memories using OWM outcome-weighted scoring.
Queries episodic and semantic memories, scores them by outcome quality, context similarity, recency, confidence, and affective modulation. Returns ranked memories with score breakdown.
Use order="losses_first" right before placing a trade: losing trades taken in similar conditions rank first, and the current mood (a losing streak) no longer pushes them down.
Inputs: symbol (required), market_context (required), limit, order, +6 more. Returns: object
remember_tradeA
Store a trade into OWM multi-layer memory with automatic updates.
Writes to episodic memory and automatically updates semantic (Bayesian), procedural (running averages + hold time + Kelly), and affective (EWMA confidence/streaks). Also writes to trade_records for backward compatibility.
Inputs: pnl (required), symbol (required), direction (required), exit_price (required), +14 more. Returns: object
validate_strategyARead-onlyIdempotent
Validate a trading strategy using statistical tests (DSR + Walk-Forward + Regime + CPCV).
For educational and research purposes only. Not financial advice.
Upload a trade log CSV (QuantConnect format) or daily returns CSV. The tool runs four statistical tests:
Deflated Sharpe Ratio (DSR) — detects overfitting from multiple testing
Walk-Forward Validation — checks out-of-sample consistency
Regime Analysis — performance across bull/bear/crisis markets
CPCV — cross-validated Sharpe stability across time periods
Inputs: file_path (required), format, strategy_name, num_strategies. Returns: object
verify_audit_chainARead-onlyIdempotent
Verify the integrity of the audit chain.
Walks the chain from from_seq (default: 1, the genesis record) to
to_seq (default: latest), checking that every record's prev_hash
matches the previous record's data_hash, and that each data_hash
equals SHA256(prev_hash || content_hash).
Returns a dict with verified, checked_count, first_break_at,
reason. A first_break_at of None with verified=True means the
chain is intact across the verified range.
Inputs: to_seq, from_seq. Returns: object
verify_audit_hashARead-onlyIdempotent
Verify the integrity of a Trading Decision Record.
Recomputes the SHA256 data_hash from stored inputs and compares with the hash computed at decision time. A mismatch indicates tampering.
Inputs: trade_id (required). Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 20 tools
Most tools target clearly distinct resources and actions, and namespaces (evolution_*, verify_audit_*) help group related operations. However, check_trade_legitimacy vs compute_dqs (both pre-trade gates) and get_agent_state vs get_behavioral_analysis (both aggregate state) have overlapping boundaries an agent could misselect between.
Nearly all tools follow a predictable snake_case verb_noun pattern (get_*, create_*, verify_*, check_*), with the evolution_* prefix used consistently as a namespace for that subgroup. Minor deviation is the mixed imperative/noun style of remember_trade, recall_memories, and compute_dqs, but the convention remains readable throughout.
20 tools is on the heavier side but justified by the breadth of the domain (memory, planning, strategy evolution, audit, validation). Each tool maps to a distinct capability rather than being redundant, so the count is reasonable though slightly toward the upper bound.
Coverage is strong: memory write/recall, planning create/check, a full evolution loop, and a complete audit trail (export, hash, chain, Merkle root). The notable gap is the planning lifecycle—create_trading_plan mentions manual cancellation but no cancel/update plan tool exists, and there is no delete/update for stored trades.
Maintenance
Related MCP Connectors
Trading MCP server for AI agents, with live market data, account reads and controlled execution.
Persistent memory for AI agents to retain, retrieve, and recall conversation context through MCP.
MCP server for Mudrex futures trading enabling AI agents to securely access data and risk tools.
An MCP memory server. One memory your agents share — across models, devices and apps.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceAn MCP server that provides persistent memory for AI agents by storing session snapshots, factual memories, and conversation summaries. It enables seamless continuity between interactions by allowing agents to restore previous emotional states and recall relevant past experiences.-
- AlicenseAqualityBmaintenanceMCP server for persistent, compounding memory that automatically captures corrections and insights across AI sessions, enabling agents to learn and improve over time.5377MIT
- AlicenseNot gradedqualityCmaintenanceMCP server that provides AI agents with persistent memory, cross-agent sharing, and context management, enabling them to remember conversations, track complex tasks, and evolve skills across tools.2MIT
- FlicenseNot gradedqualityDmaintenanceAn MCP server that captures and stores user decisions during AI-agent interactions, offering structured decision memory, cognitive bias detection, and personalized advice from historical patterns.2-