by mnemox-ai
Provides AI trading agents with a persistent, outcome‑weighted cognitive memory layer that records trade decisions, contexts, and results, then surfaces the most relevant past experiences to improve future actions.
TradeMemory Protocol implements a five‑type cognitive memory system (episodic, semantic, procedural, affective, prospective) for AI‑driven trading agents. It logs every trade with full market context, scores memories by outcome‑weighted recall, and feeds the highest‑scoring memories back to the agent for better decision‑making, bias detection, and dynamic risk sizing.
pip install tradememory-protocol
python -m src.tradememory.server
remember_trade, recall_memories) or through the REST API endpoints such as /trade/record_decision, /trade/record_outcome, /owm/recall_memories./reflect/run_daily (or similar) endpoints to generate strategy adjustments.Q × Sim × Rec × Conf × Aff.Q: Does the system trade automatically? A: No. It only stores and recalls trade information; execution must be performed by your own trading engine or broker connector.
Q: Which brokers are supported? A: Built‑in sync scripts for MetaTrader 5, Binance spot, and Alpaca. Any platform can send data via the MCP tools or REST API.
Q: Do I need an API key? A: Core memory functions run locally without keys. Optional LLM‑based reflections (Claude) require a Claude API key.
Q: Can I use the protocol without MT5? A: Absolutely. You can manually record trades or integrate any data source via the API.
Q: Is the memory layer compatible with existing v0.3.x projects?
A: Yes. Legacy tools remain functional, and recall_similar_trades automatically upgrades to OWM when episodic data exists.
Q: How is security handled? A: All data is stored locally in SQLite/JSON. If exposing the FastAPI server, secure it with standard HTTPS and authentication mechanisms.
A Mnemox Project — MCP server that gives AI trading agents persistent, outcome-weighted memory.
Works with: Claude Desktop · Claude Code · Cursor · Windsurf · any MCP client
Your AI trading agent has no memory. Every session starts from zero — same mistakes, same blown setups, no learning.
Session 1: Agent loses $200 on Asian session breakouts
Session 2: Agent loses $180 on Asian session breakouts ← no memory of Session 1
Session 3: Agent loses $210 on Asian session breakouts ← still no memory
pip install tradememory-protocol
Session 1: Agent loses $200 → remember_trade stores context + outcome
Session 2: Agent calls recall_memories → "Asian breakouts: 0% win rate, -$590"
Agent skips the trade. ← memory saved $180
Q × Sim × Rec × Conf × Aff to surface the right memory at the right time10 MCP tools · 737 tests · MIT license · All v0.3.x features work unchanged
No API key needed. Runs 30 simulated trades through the full pipeline:
git clone https://github.com/mnemox-ai/tradememory-protocol.git
cd tradememory-protocol
pip install -e .
python scripts/demo.py
── Step 1: Recording trades to memory ──
# │ Result │ Session │ Strategy │ P&L │ R
1 │ LOSS │ Asia │ Pullback │ $-15.00 │ -1.0
2 │ WIN │ London │ VolBreakout │ $+42.00 │ +2.1
3 │ WIN │ London │ VolBreakout │ $+28.50 │ +1.5
...
30 │ WIN │ London │ Pullback │ $+28.00 │ +1.4
Total: 30 trades | Winners: 19 | Win rate: 63% | Net P&L: $+499.50
── Step 2: Reflection engine discovers patterns ──
Pattern │ Win Rate │ Record │ Net P&L │ Assessment
London session │ 100% │ 14W / 0L │ $+608.50 │ HIGH EDGE
Asian session │ 10% │ 1W / 9L │ $-156.00 │ WEAK
VolBreakout strategy│ 73% │ 11W / 4L │ $+429.50 │ HIGH EDGE
── Step 3: Strategy adjustments generated ──
Parameter │ Old │ New │ Reason
london_max_lot │ 0.05 │ 0.08 │ London WR 100% — earned more room
asian_max_lot │ 0.05 │ 0.025│ Asian WR 10% — reduce exposure
min_confidence_threshold │ 0.40 │ 0.55 │ Trades below 0.55 have 0% WR
All demo data is simulated. See Before/After Comparison for detailed breakdown.
Add to your claude_desktop_config.json:
{
"mcpServers": {
"tradememory": {
"command": "uvx",
"args": ["tradememory-protocol"]
}
}
}
~/Library/Application Support/Claude/claude_desktop_config.json%APPDATA%\Claude\claude_desktop_config.jsonRestart Claude Desktop. You'll see TradeMemory tools in the 🔨 menu. Try asking:
claude mcp add tradememory -- uvx tradememory-protocol
Then ask Claude:
Add to .cursor/mcp.json (or your client's MCP config):
{
"mcpServers": {
"tradememory": {
"command": "uvx",
"args": ["tradememory-protocol"]
}
}
}
git clone https://github.com/mnemox-ai/tradememory-protocol.git
cd tradememory-protocol
pip install -e .
python -m src.tradememory.server
# Runs on http://localhost:8000
docker compose up -d
# Or manually:
docker build -t tradememory .
docker run -p 8000:8000 -e ANTHROPIC_API_KEY=your-key tradememory
Give your OpenClaw agent trading memory:
Install this skill: https://github.com/mnemox-ai/tradememory-protocol
Then tell your agent via WhatsApp:
See .skills/tradememory/SKILL.md for the full skill reference.
Legacy compatibility: All v0.3.x tools and data remain functional.
recall_similar_tradesauto-detects whether OWM episodic data exists — if yes, it uses outcome-weighted scoring; if no, it falls back to keyword matching. Zero migration required.
Outcome-Weighted Memory is a novel application of established cognitive science to AI trading agents — not an invention of new theory. It combines Tulving's episodic memory taxonomy (1972), Anderson's ACT-R activation framework (2007), Kelly's optimal bet sizing (1956), and Damasio's somatic marker hypothesis (1994) into a single recall function purpose-built for sequential financial decisions.
The core recall formula scores each candidate memory m given current context C:
Score(m, C) = Q(m) × Sim(m, C) × Rec(m) × Conf(m) × Aff(m)
| Component | Formula | What It Does |
|---|---|---|
| Q — Outcome Quality | sigmoid(k · pnl_r / σ_r) |
Maps R-multiple outcomes to (0,1) via sigmoid. A +3R winner scores 0.98; a -3R loser scores 0.02 but never zero — losing memories are recalled as warnings. |
| Sim — Context Similarity | Gaussian kernel over ContextVector |
Measures how similar the current market context (symbol, regime, ATR, session) is to when the memory was formed. Irrelevant memories are suppressed. |
| Rec — Recency | (1 + age_days/τ)^(-d) |
ACT-R power-law decay. A 30-day-old memory retains 70.7% strength; a 1-year-old memory retains 27.5%. Much gentler than exponential — old regime-relevant memories remain retrievable. |
| Conf — Confidence | 0.5 + 0.5 · confidence |
Memories formed during high-confidence states score higher. Floor of 0.5 prevents early memories from being ignored. |
| Aff — Affective Modulation | 1.0 + α · relevance(m, state) |
Current drawdown/streak state modulates recall. During drawdowns, cautionary memories surface; during winning streaks, overconfidence checks activate. |
Academic foundations:
Full specification: docs/OWM_FRAMEWORK.md (1,875 lines, includes mathematical proofs, boundary analysis, and financial validation against Kelly/Bayesian/Prospect Theory)
| Tool | Description |
|---|---|
store_trade_memory |
Store a trade decision with full context into memory |
recall_similar_trades |
Find past trades with similar market context (auto-upgrades to OWM when episodic data exists) |
get_strategy_performance |
Aggregate performance stats per strategy |
get_trade_reflection |
Deep-dive into a specific trade's reasoning and lessons |
| Tool | Description |
|---|---|
remember_trade |
Store a trade into all five memory layers simultaneously (episodic + Bayesian semantic update + procedural running averages + affective EWMA) |
recall_memories |
Outcome-weighted recall with full score breakdown per component |
get_behavioral_analysis |
Procedural memory analysis: hold times, disposition ratio, lot sizing variance, Kelly comparison |
get_agent_state |
Current affective state: confidence, risk appetite, drawdown %, win/loss streaks, recommended action |
create_trading_plan |
Store a conditional plan in prospective memory (e.g., "if regime changes to ranging, skip breakout trades") |
check_active_plans |
Match active plans against current market context, expire stale plans |
POST /trade/record_decision — Log entry decision with full contextPOST /trade/record_outcome — Log trade result (P&L, exit reason)POST /trade/query_history — Search past trades by strategy/date/resultPOST /reflect/run_daily — Trigger daily summary (rule-based, or LLM with API key)POST /reflect/run_weekly — Weekly deep reflectionPOST /reflect/run_monthly — Monthly reflectionPOST /risk/get_constraints — Dynamic risk parametersPOST /risk/check_trade — Validate trade against constraintsPOST /mt5/sync — Sync trades from MetaTrader 5POST /reflect/generate_adjustments — Generate L3 strategy adjustments from L2 patternsGET /adjustments/query — Query strategy adjustments by status/typePOST /adjustments/update_status — Update adjustment lifecycle (proposed→approved→applied)/owm/ prefix — episodic/semantic/procedural/affective/prospective CRUD + recall + Kelly sizingFull API reference: docs/API.md
scripts/mt5_sync.py) — auto-sync trades from MetaTrader 5scripts/binance_sync.py) — poll and sync spot tradesdemo.py)Sync live trades from MetaTrader 5 into TradeMemory automatically.
Tools → Options → Expert Advisors → Allow Algo Trading
Api=1 in common.ini under [Experts] section# 1. Install dependencies
pip install MetaTrader5 python-dotenv requests fastapi uvicorn pydantic
# 2. Configure .env
cp .env.example .env
# Edit .env with your MT5 credentials
# 3. Start both services
scripts/start_services.bat
# Run as Administrator:
scripts\install_autostart.bat
This registers a Windows Task Scheduler task that starts the tradememory server and scripts/mt5_sync.py 30 seconds after login.
scripts/
├── start_services.bat # Start tradememory server + mt5_sync.py
├── stop_services.bat # Stop all services
├── install_autostart.bat # Register auto-start task (run as admin)
└── TradeMemory_AutoStart.xml # Task Scheduler config
# Terminal 1: Start API server
python -c "import sys; sys.path.insert(0, 'src'); from tradememory.server import main; main()"
# Runs on http://localhost:8000
# Terminal 2: Start MT5 sync (scans every 60s)
python scripts/mt5_sync.py
# Windows: Import start_daily_reflection.bat into Task Scheduler (23:55 daily)
# Linux/Mac: 55 23 * * * /path/to/daily_reflection.sh
See MT5 Setup Guide for detailed configuration.
Does TradeMemory connect directly to my broker?
No. TradeMemory is a memory layer, not a trading platform connector. It accepts standardized trade data from any source. For MT5 users, scripts/mt5_sync.py automatically polls and syncs closed trades every 60 seconds.
What trading platforms are supported?
Any platform that can output trade data. Built-in connectors: MetaTrader 5 (scripts/mt5_sync.py) and Binance spot (scripts/binance_sync.py). For other platforms (Alpaca, Interactive Brokers), send trades through the MCP remember_trade tool or REST API.
What data does it store? Five memory types: Episodic (individual trade events with full context), Semantic (Bayesian beliefs about strategy effectiveness, updated with each trade), Procedural (behavioral patterns — hold times, disposition ratio, lot sizing variance), Affective (agent confidence, drawdown state, win/loss streaks), and Prospective (conditional trading plans). Plus the legacy L1/L2/L3 layers for backward compatibility.
Is it free to use? Yes. MIT license, fully open source. All 10 MCP tools work without any API keys. The optional LLM reflection feature requires a Claude API key for deeper insights, but the core memory system — including OWM recall and Kelly sizing — runs entirely locally.
Can I use it without MetaTrader 5?
Yes. MT5 is just one data source. You can manually store trades via the MCP store_trade_memory or remember_trade tools, send them through the REST API, or write a custom sync script for your platform.
We used TradeMemory's episodic memory system to run controlled A/B experiments on LLM trading agents. Key finding: naively adding memory made the agent worse (Profit Factor 2.42 → 0.94) due to positive recall bias — the same cognitive bias documented in human investors.
I Gave My Trading Agent Memory. It Made Everything Worse. Here's How I Fixed It.
The full experiment was conducted using the Trade Dreaming replay engine built on top of this protocol.
See CONTRIBUTING.md for guidelines.
MIT — see LICENSE.
This software is for educational and research purposes only. It does not constitute financial advice. Trading involves substantial risk of loss. You are solely responsible for your trading decisions. The authors accept no liability for losses incurred through use of this software.
Built by Mnemox
Please log in to share your review and rating for this MCP.
Explore related MCPs that share similar capabilities and solve comparable challenges
by stripe
Provides SDKs and tools to integrate Stripe's billing and API services with large language models, agent frameworks, and token‑metering for AI‑powered products and businesses.
by goat-sdk
Enables AI agents to send and receive payments, purchase goods and services, execute investment strategies, tokenize assets, and obtain financial insights by leveraging blockchains, stablecoins, and wallets.
by financial-datasets
Provides access to income statements, balance sheets, cash flow statements, stock prices, market news, and cryptocurrency data through MCP tools for AI assistants.
by alpacahq
Enables large language models to trade stocks and options, retrieve real‑time and historical market data, and manage portfolios using plain English commands through a local or remote MCP server.
by stefanoamorelli
Provides an MCP server that connects AI models to SEC EDGAR filings, enabling real‑time retrieval of company filings, financial statements, and insider‑trading data with exact XBRL precision and verifiable filing references.
by ariadng
Enables AI LLMs to execute trades on the MetaTrader 5 platform through the Model Context Protocol.
by XeroAPI
Provides a bridge between the Model Context Protocol and Xero's API, enabling standardized access to Xero accounting and business features.
by kukapay
Provides a comprehensive set of cryptocurrency technical analysis indicators and ready‑to‑use trading strategies through an MCP interface, enabling AI agents and applications to generate buy, hold, or sell signals.
by kukapay
Integrates the Freqtrade cryptocurrency trading bot with MCP, exposing its REST API as tools for AI agents to perform automated trading operations.