Tradememory Protocol

io.github.mnemox-ai由 GitHub 账号 mnemox-ai 发布v0.5.6更新于 Oct 30, 2026

Tamper-evident decision audit trail and outcome-weighted memory for AI trading agents.

概览

AI 生成的概览

面向 AI 交易代理的本地优先记忆与审计服务器:记录交易、在下单前召回亏损交易,并可按你的策略拦截订单。

可以做什么
  • 记录与召回交易,按结果加权评分,支持亏损优先召回与行为分析
  • 读取代理状态、策略表现、交易反思与进行中的交易计划
  • 执行交易前风险检查、策略验证与数据质量评分
  • 借助行情数据、模式发现与回测生成并演化策略
  • 导出并校验 SHA-256 链式审计记录,含每日 Merkle 根
  • 可选地代理券商 MCP 服务器,按你的策略评估或拒绝下单类工具
适用场景
当 AI 代理实际交易或起草交易,而你希望它在提出订单前看到自己过去的亏损交易、保留防篡改的决策记录,或在 Alpaca 等券商连接前加一道策略闸门时适用。
运行要求
以本地 Python 包运行(pip 或 uvx;proxy 附加组件需 Python 3.12+)。记忆服务器与 Hyperliquid 公开成交数据无需密钥;Alpaca 同步使用本地 env 文件中的只读密钥。可选密钥:ANTHROPIC_API_KEY 用于演化与回放,DISCORD_WEBHOOK_URL 用于 MT5 摘要。行情同步、Binance 数据与 RFC 3161 时间戳需要网络。
安装前请注意
proxy 附加组件会把允许的订单转发给券商,策略配置错误可能产生真实交易;券商密钥只交给代理启动的券商进程。对外调用包括每日根哈希的 RFC 3161 时间戳(默认开启,可用 TRADEMEMORY_TSA=off 关闭)、行情同步、Binance 公开数据,以及可选的 Anthropic、DeepSeek、Hugging Face 与 Discord 调用。审计链只能防篡改检测,无法阻止整体重写,README 也声明这不构成合规结论。

安装

在 SourceWeft 中

  1. 打开 控制台中的 Tradememory Protocol,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

[TradeMemory Protocol]


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

bash
pip install tradememory-protocol
# Hyperliquid: public fills, no key neededtradememory sync hyperliquid --address 0xYourAddress
# Alpaca: read-only calls with your own keys, kept in a local filetradememory sync alpaca --env-file ~/.secrets/alpaca.env

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

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

bash
pip install tradememory-protocol

Add to Claude Desktop (claude_desktop_config.json):

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 / Cursor / Docker
bash
# Claude Codeclaude mcp add tradememory -- uvx tradememory-protocol
# From sourcegit clone https://github.com/mnemox-ai/tradememory-protocol.gitcd tradememory-protocol && pip install -e . && python -m tradememory
# Dockerdocker compose up -d

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

bash
pip install "tradememory-protocol[proxy]"   # Python 3.12+tradememory proxy init --account-id <your Alpaca account id> --symbols AAPL,MSFTtradememory proxy doctor --env-file ~/.secrets/alpaca-paper.env   # checks the live tool names and the account idtradememory proxy config                                           # prints the MCP client entry that replaces the direct Alpaca one

Refused 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 traderForex EA systemAudit trail (illustrative)
MarketStocks (AAPL, TSLA, ...)XAUUSD (Gold)Multi-asset
HowPre-flight checklist before every tradeAutomated sync from MT5Decision records with a hash chain
WhoOne independent user (March 2026)The maintainer's own MT5 accountAn example, not a customer
DetailsRead moreRead moreRead more

How it works

[OWM 5 Factors]

  1. Recall — Before trading, retrieve past trades weighted by outcome quality, context similarity, recency, confidence, and emotional state (OWM Framework)
  2. Record — After trading, one call to remember_trade writes to five memory layers: episodic, semantic, procedural, affective, and trade records
  3. Reflect — Daily/weekly/monthly reviews detect behavioral drift, strategy decay, and trading mistakes
  4. Audit — Every decision is SHA-256 hashed at creation and chained to the one before. Export anytime for review

MCP Tools

CategoryToolsDescription
Memoryremember_trade · recall_memoriesRecord and recall trades with outcome-weighted scoring
Stateget_agent_state · get_behavioral_analysisConfidence, drawdown, streaks, behavioral patterns
Planningcreate_trading_plan · check_active_plansProspective plans with conditional triggers
Riskcheck_trade_legitimacy5-factor pre-trade gate (full / reduced / skip)
Auditexport_audit_trail · verify_audit_hashSHA-256 tamper detection + bulk export
All 20 MCP tools + REST API
CategoryTools
Core Memoryget_strategy_performance · get_trade_reflection
OWM Cognitiveremember_trade · recall_memories · get_behavioral_analysis · get_agent_state · create_trading_plan · check_active_plans
Risk & Governancecheck_trade_legitimacy · validate_strategy · compute_dqs
Evolutionevolution_fetch_market_data · evolution_discover_patterns · evolution_run_backtest · evolution_evolve_strategy · evolution_get_log
Auditexport_audit_trail · verify_audit_hash · verify_audit_chain · get_daily_root

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.

RegulationRequirementTradeMemory Coverage
MiFID II Article 17Record every algorithmic trading decision factorFull decision chain: conditions, filters, indicators, execution
EU AI Act Article 14Human oversight of high-risk AI systemsExplainable reasoning + memory context for every decision
EU AI Act Article 12Automatic, tamper-resistant logs over system lifetimeLinked SHA-256 chain + daily Merkle roots (RFC 3161 TSA anchoring, on by default since 0.5.3)
bash
# Verify a single record hasn't been tampered withverify_audit_hash(trade_id="MT5-7047640363")# → {"verified": true, "chain_entry": {"sequence_num": 42, ...}}
# Walk the entire chain (or a slice) end-to-endverify_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 dayget_daily_root(date="2026-05-14")# → {"verified": true, "root_hash": "a05544...", "record_count": 18}
# Bulk exportGET /audit/export?strategy=VolBreakout&start=2026-03-01&format=jsonl

Daily 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 hyperliquid reads public data with no key. tradememory sync alpaca makes read-only calls with keys from a file on your machine. Synced trades stay in your local database.
  • Brake (proxy extra). 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=off turns it off). tradememory sync calls 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 set ANTHROPIC_API_KEY. Replay calls DeepSeek by default (or Anthropic), and only with that provider's key set. If you install sentence-transformers for hybrid recall, it downloads its model from Hugging Face on first use. The MT5 and Binance sync scripts in scripts/ read their credentials from your environment, and the MT5 one posts trade summaries (symbol, prices, P&L) to a Discord webhook only if you set DISCORD_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

DocDescription
Getting StartedInstall → first trade → pre-flight checklist
Use Cases3 usage scenarios, each labelled first-party or independent
API ReferenceAll REST endpoints
OWM FrameworkOutcome-Weighted Memory theory
ArchitectureSystem design & layer separation
TutorialDetailed walkthrough
MT5 SetupMetaTrader 5 integration
Research LogEvolution experiments & data
Failure Taxonomy11 trading AI failure modes
中文版Traditional Chinese

Contributing

See Contributing Guide · Security Policy

[Star History]

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.

Built by Mnemox

来源:README.md,提交 c87372a

工具

0
SourceWeft 尚未在沙箱中启动过该软件包,因此其工具未知。

版本历史

2
  1. v0.5.6最新Oct 2, 2026
  2. v0.5.5Sep 16, 2026

评分

已满足适用检查项的 50%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分