Skip to main content
Glama
TradeMemory Protocol

TradeMemory Protocol

by mnemox-ai

PyPI Tests MCP Tools Smithery License: MIT

Начало работы | Примеры использования | Справочник API | Фреймворк OWM | Ограничения | 中文版


Статус проекта (август 2026): Функционально завершён, в режиме сопровождения — сообщения об ошибках и уязвимостях по-прежнему рассматриваются; новые функции и облачный сервис не планируются. По платным услугам см. Анализ торговых записей.

Ваш торговый ИИ страдает амнезией. И регуляторы начинают это замечать.

Он совершает одни и те же ошибки в каждой сессии. Он не может объяснить, почему торговал. Он забывает всё, когда заканчивается контекстное окно. Тем временем MiFID II ужесточает требования к документированию алгоритмических решений (Статья 17). Закон ЕС об ИИ требует систематического логирования действий ИИ (Статья 14). Агенты ваших конкурентов учатся на каждой сделке.

В стеке ИИ-трейдинга не хватает одного слоя. Каждый MCP-сервер занимается исполнением — размещением ордеров, получением цен, чтением графиков. Ни один не занимается памятью.

Ваш агент может купить 100 акций AAPL, но не может ответить: «Что произошло в прошлый раз, когда я покупал AAPL в таких условиях?»

TradeMemory — это слой памяти. Одна команда pip install — и ваш ИИ-агент запоминает каждую сделку, каждый результат, каждую ошибку — с защищённым от подделки журналом аудита на основе SHA-256.

Используется в продакшене трейдерами, которые выполняют предторговые чек-листы перед каждой позицией, и советниками (EA), ежедневно записывающими тысячи решений.

Что он делает

  • Перед торговлей: спросите свою память — что произошло в прошлый раз в таких рыночных условиях? Чем это закончилось?

  • После торговли: один вызов записывает всё — пять слоёв памяти обновляются автоматически

  • Предохранители: отслеживание уверенности, оповещения о просадке, обнаружение серий убытков — система говорит вам, когда остановиться

Работает с любым рынком (акции, форекс, криптовалюты, фьючерсы), любым брокером, любой ИИ-платформой. TradeMemory не исполняет сделки и не касается ваших денег — он только записывает и вспоминает.

Related MCP server: AgentRecall

Быстрый старт

pip install tradememory-protocol

Добавьте в Claude Desktop (claude_desktop_config.json):

{
  "mcpServers": {
    "tradememory": {
      "command": "uvx",
      "args": ["tradememory-protocol"]
    }
  }
}

Затем скажите Claude: «Запиши мою длинную позицию по AAPL по $195 — превышение прибыли, институциональные покупки, высокая уверенность».

# 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 -d

Полное руководство: Начало работы (трек трейдера + трек разработчика)

Кто использует TradeMemory

Трейдер акций США

Советник для Forex

Отдел комплаенса

Рынок

Акции (AAPL, TSLA, ...)

XAUUSD (золото)

Мультиактив

Как

Предторговый чек-лист перед каждой сделкой

Автоматическая синхронизация с MT5

Полный аудит решений

Ключевая ценность

Система дисциплины — память перед каждым решением

Запись причин блокировки сигналов, а не только исполнения

Записи с защитой от подделки SHA-256 для регуляторов

Подробнее

Подробнее →

Подробнее →

Подробнее →

Как это работает

  1. Вспомнить — Перед торговлей извлеките прошлые сделки, взвешенные по качеству результата, схожести контекста, давности, уверенности и эмоциональному состоянию (Фреймворк OWM)

  2. Записать — После торговли один вызов remember_trade записывает данные в пять слоёв памяти: эпизодический, семантический, процедурный, аффективный и записи о сделках

  3. Проанализировать — Ежедневные/еженедельные/ежемесячные обзоры выявляют поведенческие отклонения, деградацию стратегии и торговые ошибки

  4. Аудит — Каждое решение хешируется SHA-256 при создании. Экспорт в любое время для проверки или подачи регуляторам

Инструменты MCP

Категория

Инструменты

Описание

Память

remember_trade · recall_memories

Запись и извлечение сделок с оценкой по результатам

Состояние

get_agent_state · get_behavioral_analysis

Уверенность, просадка, серии, поведенческие паттерны

Планирование

create_trading_plan · check_active_plans

Перспективные планы с условными триггерами

Риск

check_trade_legitimacy

Предторговый шлюз из 5 факторов (полный / сокращённый / пропуск)

Аудит

export_audit_trail · verify_audit_hash

Обнаружение подделки SHA-256 + массовый экспорт

Категория

Инструменты

Основная память

get_strategy_performance · get_trade_reflection

Когнитивные OWM

remember_trade · recall_memories · get_behavioral_analysis · get_agent_state · create_trading_plan · check_active_plans

Риск и управление

check_trade_legitimacy · validate_strategy · compute_dqs

Эволюция

evolution_fetch_market_data · evolution_discover_patterns · evolution_run_backtest · evolution_evolve_strategy · evolution_get_log

Аудит

export_audit_trail · verify_audit_hash · verify_audit_chain · get_daily_root

REST API: 35+ конечных точек для записи сделок, рефлексий, риска, синхронизации с MT5, OWM, эволюции и аудита. Полный справочник →

Анализ торговых записей

Сам TradeMemory бесплатен и размещается локально. Платная услуга, которую предлагает сопровождающий, — это статистический анализ ваших собственных торговых записей: экспортируйте свою историю MT4/MT5 и получите отчёт по описательной статистике — где сосредоточены ваши убытки, как меняется размер позиции после убытков, структура принудительной ликвидации и фактический риск на сделку, — а затем разбор по видеозвонку.

Только описательная статистика прошлых сделок: никаких торговых сигналов, инвестиционных советов или обещаний доходности. Ваши файлы удаляются после передачи.

dev@mnemox.ai | Записаться на звонок

Корпоративное использование и комплаенс

Каждое торговое решение вашего агента — включая решения не торговать — записывается как запись торгового решения (TDR). Хеши содержимого SHA-256 для каждой записи связываются в прямую цепочку аудиторского журнала; каждый день UTC обобщается корнем Меркла, который сам связывает дни. Вмешательство в любую историческую запись делает недействительными все последующие ссылки.

Регламент

Требование

Покрытие TradeMemory

MiFID II, статья 17

Записывать каждый фактор алгоритмического торгового решения

Полная цепочка решений: условия, фильтры, индикаторы, исполнение

Закон ЕС об ИИ, статья 14

Надзор человека за ИИ-системами высокого риска

Объяснимое обоснование + контекст памяти для каждого решения

Закон ЕС об ИИ, статья 12

Автоматические, защищённые от подделки журналы на весь срок службы системы

Связанная цепочка SHA-256 + ежедневные корни Меркла (RFC 3161 TSA в фазе 1.5)

# 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 for regulatory submission
GET /audit/export?strategy=VolBreakout&start=2026-03-01&format=jsonl

См. LIMITATIONS.md для полного заявления о зрелости цепочки аудита, включая то, чего ещё нет в v0.5.2 (метки времени TSA, внешнее якорение, доказательство вывода zkML).

Нужно индивидуальное развёртывание для вашего фонда? → dev@mnemox.ai

Безопасность

  • Никогда не касается API-ключей. TradeMemory не исполняет сделки, не перемещает средства и не получает доступ к кошелькам.

  • Только чтение и запись. Ваш агент передаёт контекст решения в TradeMemory. Он его хранит. И всё.

  • Локальный приоритет. Единственный исходящий вызов — это доверенная метка времени RFC 3161 для ежедневных корней аудита — 32-байтовый хеш, без торговых данных (включено по умолчанию; отключить с помощью TRADEMEMORY_TSA=off). Больше ничего не покидает вашу машину.

  • Связанный аудиторский журнал SHA-256. Каждая запись хешируется при создании и связывается с предыдущей. Ежедневные корни Меркла закрепляют цепочку. Проверяйте целостность на уровне записи, среза или дня. Подделка обнаруживается на любом уровне; внешнее якорение (TSA по умолчанию) — в дорожной карте.

  • Более 1400 проходящих тестов. Полный набор тестов с CI.

Статус исследований

Фреймворк OWM TradeMemory основан на когнитивной науке (Tulving 1972) и обучении с подкреплением (Schaul et al. 2015). Текущий статус:

  • Пятифакторная оценка OWM: реализована, протестирована (более 1400 тестов)

  • Статистическая валидация: DSR, MBL реализованы (Bailey-de Prado 2014)

  • Журнал аудита: защищённые от подделки TDR на основе SHA-256

  • Эволюционный движок: исследовательская фаза (генерация стратегий работает, доля прохождения статистического шлюза в процессе оптимизации)

  • Гибридное извлечение: активен режим только OWM, векторное слияние доступно при настройке эмбеддингов

  • Эмпирическая валидация: продолжается (n=40 сделок, целевое n>=100 для статистической значимости)

Документация

Документ

Описание

Getting Started

Установка → первая сделка → предстартовый чек-лист

Use Cases

3 реальных производственных сценария

API Reference

Все REST-эндпоинты

OWM Framework

Теория Outcome-Weighted Memory

Architecture

Проектирование системы и разделение слоёв

Tutorial

Подробное руководство

MT5 Setup

Интеграция MetaTrader 5

Research Log

Эволюционные эксперименты и данные

Failure Taxonomy

11 режимов отказа торгового ИИ

中文版

Традиционный китайский

Участие

См. Руководство по участию · Политику безопасности


MIT — см. LICENSE. Только для образовательных/исследовательских целей. Не является финансовой консультацией.

Available Tools

20 tools
check_active_plansA
Idempotent

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_legitimacyA
Idempotent

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_dqsA
Idempotent

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_dataA
Idempotent

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_logA
Read-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_backtestA
Idempotent

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_trailA
Read-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_stateA
Read-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_analysisA
Read-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_rootA
Idempotent

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_performanceA
Read-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_reflectionA
Read-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_memoriesA
Idempotent

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_strategyA
Read-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:

  1. Deflated Sharpe Ratio (DSR) — detects overfitting from multiple testing

  2. Walk-Forward Validation — checks out-of-sample consistency

  3. Regime Analysis — performance across bull/bear/crisis markets

  4. CPCV — cross-validated Sharpe stability across time periods

Inputs: file_path (required), format, strategy_name, num_strategies. Returns: object

verify_audit_chainA
Read-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_hashA
Read-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

    A4/5.0

    Scored across 20 tools

    Disambiguation4/5

    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.

    Naming Consistency4/5

    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.

    Tool Count4/5

    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.

    Completeness4/5

    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

    ActivitySlowing
    ResponsivenessMixed handling

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      An 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.
      -
    • A
      license
      A
      quality
      B
      maintenance
      MCP server for persistent, compounding memory that automatically captures corrections and insights across AI sessions, enabling agents to learn and improve over time.
      5
      376
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      MCP 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.
      2
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      An 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
      -