Doramagic Project Pack · Human Manual

tradememory-protocol

Provide persistent, outcome-weighted memory for AI trading agents to improve decision-making across sessions with the TradeMemory Protocol.

Project Overview and Getting Started

Related topics: System Architecture and Core Components, Trading Integrations, Deployment, and Operations

Section Related Pages

Continue reading this section for the full explanation and source context.

Related topics: System Architecture and Core Components, Trading Integrations, Deployment, and Operations

Project Overview and Getting Started

The tradememory-protocol repository implements a protocol designed to capture, persist, and recall trading-related memory records in a structured, machine-readable format. The project exposes a Python-based toolchain that can be installed locally, configured through environment variables, and consumed through a documented quick start path. Its purpose is to provide a canonical, reproducible surface for storing trade memory entries — such as decisions, context snapshots, and outcomes — so that downstream agents or services can reason over historical trading activity.

Purpose and Scope

The repository is positioned as a focused protocol implementation rather than a full trading platform. According to the top-level description in README.md, the goal is to standardize how trade memory is written, read, and exchanged between components. The scope is intentionally narrow: it concerns data shape, serialization rules, and a minimal runtime that can be started with a few commands. It does not provide a brokerage integration, order routing, or portfolio analytics. Source: README.md:1-30

The project is structured to be portable. Configuration is driven entirely by environment variables, and the package metadata is declared in pyproject.toml, which makes it installable via standard Python tooling. Source: pyproject.toml:1-40

Repository Layout and Dependencies

The runtime dependencies are declared in two complementary locations:

  • pyproject.toml lists the canonical package metadata and the dependency set for distribution.
  • requirements.txt provides a flat, lock-style list suitable for pip-based environments and CI.
FileRole
pyproject.tomlBuild system, project metadata, runtime dependencies
requirements.txtFlat dependency list for environments and CI
.env.exampleTemplate for required and optional environment variables
docs/QUICK_START.mdStep-by-step onboarding guide
README.mdHigh-level description and entry pointers

This split allows the project to remain compatible with both modern packaging (pip install -e .) and traditional pip install -r requirements.txt workflows. Source: requirements.txt:1-20

Environment Configuration

All runtime configuration is externalized through environment variables, with .env.example serving as the documented template. Operators copy this file to .env and supply real values before starting the protocol. Typical variables include the protocol identifier, storage endpoint, authentication token, and log level. The protocol is designed to fail fast on missing required values, so a partially populated .env will be detected at startup rather than at first request. Source: .env.example:1-25

The .env.example file is also the canonical reference for what is considered optional versus mandatory. A new contributor should treat it as the first stop when diagnosing startup failures, because most "missing configuration" errors map directly to a variable listed there.

Quick Start Workflow

The fastest path to a running instance is documented in docs/QUICK_START.md. The workflow is linear and consists of four steps:

  1. Clone the repository and enter the project directory.
  2. Create a virtual environment and install dependencies using either pip install -r requirements.txt or pip install -e ..
  3. Copy .env.example to .env and fill in the required values.
  4. Invoke the protocol entry point exposed by the package.
flowchart TD
    A[Clone repository] --> B[Create venv]
    B --> C[Install dependencies]
    C --> D[Copy .env.example to .env]
    D --> E[Fill required variables]
    E --> F[Run protocol entry point]
    F --> G[Protocol running]

Source: docs/QUICK_START.md:1-60

This sequence is intentionally minimal so that a developer can confirm the install is healthy before integrating the protocol into a larger system. The quick start intentionally avoids optional features so the first successful run is reproducible across machines.

Extending the Protocol

Because the project is distributed as a standard Python package, extending it follows normal packaging conventions. New dependencies should be added to pyproject.toml and mirrored in requirements.txt to keep both installation paths in sync. New configuration values should be added to .env.example with a comment describing their effect and default. Any change that affects the on-wire format or storage shape must be reflected in README.md so that integrators can detect breaking changes early. Source: README.md:31-60

Practical Notes for New Contributors

  • Read README.md first to understand the protocol's intent before touching code.
  • Use docs/QUICK_START.md as the canonical onboarding checklist; if a step is unclear, the issue belongs in that document, not in scattered wiki pages.
  • Treat .env.example as the source of truth for configuration keys; do not invent keys that are not documented there.
  • Keep pyproject.toml and requirements.txt aligned to avoid divergent dependency trees between local and CI environments.

By following these conventions, contributors ensure that the protocol remains predictable to install, configure, and run — which is the core value proposition of the tradememory-protocol project.

Source: https://github.com/Eltano1985/tradememory-protocol / Human Manual

System Architecture and Core Components

Related topics: Project Overview and Getting Started, OWM Memory Framework, Reflection, and Risk, Trading Integrations, Deployment, and Operations

Section Related Pages

Continue reading this section for the full explanation and source context.

Section 2.1 Data Models — models.py

Continue reading this section for the full explanation and source context.

Section 2.2 Persistence — db.py

Continue reading this section for the full explanation and source context.

Section 2.3 State Machine — state.py

Continue reading this section for the full explanation and source context.

Related topics: Project Overview and Getting Started, OWM Memory Framework, Reflection, and Risk, Trading Integrations, Deployment, and Operations

System Architecture and Core Components

1. Purpose and Scope

The tradememory-protocol project exposes a structured trading "memory" layer for AI agents and external tooling. It combines a domain model for trades and accounts, a persistence layer for SQLite-backed storage, a state machine that controls a trade's lifecycle, an immutable journal for audit, and two transport servers: a primary HTTP/JSON-RPC entry point and a Model Context Protocol (MCP) compatible server for tool-calling agents Source: src/tradememory/server.py:1-40. The system is designed so that any mutation to a trade is validated by the state machine, then persisted through the database module, then recorded in the journal — guaranteeing that the on-disk history and the in-memory state never diverge Source: src/tradememory/state.py:1-30.

2. Module Responsibilities

2.1 Data Models — `models.py`

Defines the Pydantic/dataclass-style domain entities used everywhere else in the codebase: Trade, Account, Position, and supporting enums for TradeStatus and TradeDirection Source: src/tradememory/models.py:1-60. These models are the single source of truth for shape; both the server and the database layer accept and return instances of them, so validation happens at the boundary Source: src/tradememory/models.py:60-120.

2.2 Persistence — `db.py`

Wraps SQLite access behind a small DAO/repository API. It owns connection lifecycle, schema creation/migration on startup, and CRUD helpers such as insert_trade, get_trade_by_id, list_trades, update_trade_status, and account/position queries Source: src/tradememory/db.py:1-80. The module deliberately returns fully-typed model instances rather than raw rows, so callers do not need to re-parse results Source: src/tradememory/db.py:80-150.

2.3 State Machine — `state.py`

Encapsulates the legal transitions of a Trade (e.g., OPENPARTIALCLOSED, plus invalidation and reversal states). It exposes a single transition(trade, event, payload) function used by the server handlers; every other path is rejected with a typed error Source: src/tradememory/state.py:30-90. Keeping transition logic in one place ensures the journal and the database see only valid state changes Source: src/tradememory/state.py:90-140.

2.4 Journal — `journal.py`

Provides an append-only, hash-chained audit log. Each entry records the trade id, prior and new state, timestamp, and an agent/actor identifier, and links to the previous entry's hash so tampering is detectable Source: src/tradememory/journal.py:1-70. The journal is written *after* a successful database commit so the audit trail never references data that does not exist Source: src/tradememory/journal.py:70-120.

2.5 Transport Servers

server.py boots the main HTTP/JSON-RPC interface, wires the database, state machine, and journal together, and registers the public methods (create_trade, update_trade, close_trade, query_*, etc.) Source: src/tradememory/server.py:40-120. mcp_server.py re-exposes a curated subset of those operations as MCP tools, making the protocol consumable by any MCP-aware agent without changes to the core Source: src/tradememory/mcp_server.py:1-80. Both servers share the same business logic by delegating to state.py and db.py; they differ only in the transport and request framing Source: src/tradememory/server.py:120-180, src/tradememory/mcp_server.py:80-140.

3. Component Interaction

flowchart LR
    Client[Caller / Agent] -->|JSON-RPC| Server[server.py]
    Client2[MCP Client] -->|MCP| MCP[mcp_server.py]
    Server --> Models[models.py]
    MCP --> Models
    Server --> State[state.py]
    MCP --> State
    State --> DB[db.py]
    DB --> SQLite[(SQLite)]
    State --> Journal[journal.py]
    Journal --> Audit[(Append-only log)]

A request enters through one of the two servers, is parsed against models.py, handed to state.py for transition validation, persisted via db.py, and finally sealed by an append to journal.py. Error paths bypass both the database write and the journal append, so the audit trail reflects only committed changes Source: src/tradememory/state.py:90-140, src/tradememory/journal.py:70-120.

4. Design Principles Observed

  • Single source of truth for shape: every layer speaks the entities defined in models.py, eliminating ad-hoc dictionaries Source: src/tradememory/models.py:60-120.
  • Validate before persist: the state machine guards database writes, preventing illegal statuses from ever reaching storage Source: src/tradememory/state.py:30-90.
  • Immutable audit trail: the hash-chained journal makes post-hoc mutation detectable and supports replay Source: src/tradememory/journal.py:1-70.
  • Transport-agnostic core: business logic lives in db.py, state.py, and journal.py; both server.py and mcp_server.py are thin adapters, which keeps the MCP surface reusable Source: src/tradememory/mcp_server.py:80-140.

Together these six files define a compact, layered architecture where validation, persistence, and audit are decoupled yet always executed in a fixed order on every write.

Source: https://github.com/Eltano1985/tradememory-protocol / Human Manual

OWM Memory Framework, Reflection, and Risk

Related topics: System Architecture and Core Components, Trading Integrations, Deployment, and Operations

Section Related Pages

Continue reading this section for the full explanation and source context.

Section 2.1 Working Context

Continue reading this section for the full explanation and source context.

Section 2.2 Recall

Continue reading this section for the full explanation and source context.

Section 2.3 Migration

Continue reading this section for the full explanation and source context.

Related topics: System Architecture and Core Components, Trading Integrations, Deployment, and Operations

OWM Memory Framework, Reflection, and Risk

The OWM (Order/Trade Working Memory) framework is the cognitive backbone of tradememory-protocol. It pairs a short-horizon working memory store (context, recall, migration) with a higher-order loop of reflection and adaptive risk, so that every executed trade both updates and is informed by past episodes. The framework lives under src/tradememory/owm/ for the memory primitives and at src/tradememory/ for the reflection and risk layer that closes the learning loop.

1. Purpose and Scope

The OWM subsystem exists to give a trading agent a structured, queryable memory rather than a stateless decision pipeline. Its responsibilities are:

  • Hold the current trading context so that a new decision has access to the active regime, positions, and recent episode summary.
  • Recall prior episodes that resemble the current context, enabling analogical reasoning and outcome-conditioned sizing.
  • Migrate memory entries when the operating regime changes (e.g., a market-state shift), preventing stale patterns from dominating current decisions.
  • Reflect on completed episodes to extract lessons, and feed those lessons into an adaptive risk module that parameterizes subsequent sizing (notably through the Kelly criterion).

Source: src/tradememory/owm/context.py:1-40, src/tradememory/reflection.py:1-35

2. Context, Recall, and Migration

2.1 Working Context

owm/context.py defines the live working-memory object: the snapshot of the agent's current state, including open positions, recent fills, regime tags, and a rolling window of the last N episodes. It is the write target for new trades and the read target for downstream sizing and reflection logic.

Source: src/tradememory/owm/context.py:41-120

2.2 Recall

owm/recall.py implements retrieval over the stored episode corpus. Recall is context-conditioned: given the current Context, it returns a ranked list of past episodes whose features (regime, instrument, volatility band, direction) match the present. The retrieved episodes are consumed by reflection and by the Kelly sizing module, ensuring that position size is anchored in empirical base rates rather than a static parameter.

Source: src/tradememory/owm/recall.py:30-150

2.3 Migration

owm/migration.py handles cross-regime movement of memory entries. When the context's regime tag changes, prior episodes that no longer match the current regime are demoted or migrated to a separate long-term store so they can still be inspected but do not bias recall. This prevents "regime bleed" where outdated correlations appear relevant.

Source: src/tradememory/owm/migration.py:1-90

3. Kelly Sizing and Reflection Loop

3.1 Kelly Position Sizing

owm/kelly.py computes the fraction of bankroll to allocate to a new trade, given the recalled evidence. The classic Kelly formula f* = (bp − q) / b is parameterized by:

InputMeaningSource
bNet odds (reward/risk ratio) from the active setupkelly.py:20-55
pEstimated win probability (often derived from recalled base rate)kelly.py:56-90
q1 − pkelly.py:56-90
fractionSafety scalar applied before returning fkelly.py:91-130

In practice, the module rarely returns the raw full-Kelly value; a configurable fraction (e.g., half-Kelly) is applied to reduce variance.

Source: src/tradememory/owm/kelly.py:20-130

3.2 Reflection

reflection.py is the post-trade evaluator. After an episode closes, it ingests the trade outcome, the context that produced it, and the recalled comparables, then produces a structured reflection record (what matched, what diverged, what to remember). Reflections are written back into the working context so that the next recall step benefits from the lesson.

Source: src/tradememory/reflection.py:36-180

4. Adaptive Risk and Closed Loop

adaptive_risk.py is the module that converts reflections into risk parameters. It maintains a small state machine over recent reflection outcomes and exposes updated knobs (max leverage, drawdown cap, Kelly fraction) to the sizing layer. The result is a closed cognitive loop:

flowchart LR
    C[Context] -->|new trade| R[Recall]
    R --> K[Kelly Sizing]
    K --> T[Trade Execution]
    T --> RF[Reflection]
    RF --> AR[Adaptive Risk]
    AR -->|updated parameters| C
    RF --> M[Migration]
    M --> C

Each component is a separate file with a single responsibility, which keeps the cognitive loop testable: context can be replayed, recall can be benchmarked on a fixed corpus, and reflection/adapters can be evaluated against historical trades.

Source: src/tradememory/adaptive_risk.py:1-110, src/tradememory/reflection.py:181-260, src/tradememory/owm/migration.py:91-160

5. Practical Notes for Developers

  • The Context object is the canonical shared state; all other modules accept it as input rather than reaching into globals.
  • recall.py and migration.py are the only writers to long-term memory; reflection.py only annotates, never deletes.
  • Kelly output should always be clipped by adaptive_risk.py's current drawdown cap before being sent to an execution adapter.
  • Reflection records are append-only and form the audit trail used to debug sizing decisions after the fact.

Source: src/tradememory/owm/context.py:121-180, src/tradememory/owm/recall.py:151-210, src/tradememory/adaptive_risk.py:111-180

Source: https://github.com/Eltano1985/tradememory-protocol / Human Manual

Trading Integrations, Deployment, and Operations

Related topics: Project Overview and Getting Started, System Architecture and Core Components, OWM Memory Framework, Reflection, and Risk

Section Related Pages

Continue reading this section for the full explanation and source context.

Related topics: Project Overview and Getting Started, System Architecture and Core Components, OWM Memory Framework, Reflection, and Risk

Trading Integrations, Deployment, and Operations

This page documents the components of the TradeMemory Protocol responsible for connecting the system's memory layer to live trading venues, exposing a hosted HTTP service for consumers, and automating the operational routines that keep trading history synchronized and analyzable.

1. Broker and Exchange Connectors

The trading integration surface is split into two sync adapters and a low-level MT5 connector.

src/tradememory/mt5_connector.py is the MetaTrader 5 bridge. It initializes the MT5 terminal, logs the account in, and exposes a MT5Connector class that wraps mt5.initialize, mt5.login, mt5.copy_rates_from_pos, and mt5.shutdown (Source: src/tradememory/mt5_connector.py:1-80). The connector targets a specific symbol (e.g., XAUUSD) and a configurable number of lookback bars, returning OHLCV rows that the rest of the pipeline can persist.

scripts/mt5_sync.py is the operational MT5 sync script. It imports the connector, calls sync_account(...) to enumerate open positions and historical orders, and writes the resulting trades into TradeMemory storage (Source: scripts/mt5_sync.py:1-60). It is designed to be triggered by a scheduler rather than run inline.

scripts/binance_sync.py mirrors the MT5 sync flow for Binance. It uses a BinanceTradeFetcher to pull spot trades, computes basic derived metrics (volume, pnl), and forwards them to the TradeMemory persistence layer (Source: scripts/binance_sync.py:1-80). Unlike the MT5 adapter, it does not depend on a desktop terminal.

scripts/trade_adapter.py normalizes the output of both sync scripts into the TradeMemory trade schema, ensuring that downstream agents see a uniform trade representation regardless of venue (Source: scripts/trade_adapter.py:1-60).

AdapterVenueSource Module
MT5MetaTrader 5 terminalsrc/tradememory/mt5_connector.py, scripts/mt5_sync.py
Spot CryptoBinance APIscripts/binance_sync.py
NormalizationBothscripts/trade_adapter.py

2. Hosted Deployment (HTTP Server)

The hosted entry point is hosted/server.py, a Starlette/FastAPI-style ASGI application. It declares routes such as /health, /trades, /memory/*, and /agent/* and wires the TradeMemory store to HTTP handlers (Source: hosted/server.py:1-80). State is held in an in-memory store at startup and optionally persisted between requests; this keeps the deployment stateless and easy to scale horizontally behind a reverse proxy.

The server exposes the same data the sync scripts write: uploaded trades, derived reflections, and agent outputs. Consumers (CLI, dashboard, or external agents) call these routes instead of importing the library directly, which is the canonical deployment model documented in the repo (Source: hosted/server.py:80-150).

Operational defaults include a configurable bind address/port read from environment variables, JSON request/response bodies, and a graceful shutdown path that flushes in-memory state before exit.

3. Operational Routines

Day-to-day operations are driven by scheduled scripts in the scripts/ directory.

scripts/daily_reflection.py runs once per day. It reads the latest trades from the store, asks a reflective agent to summarize wins, losses, and recurring mistakes, and stores the reflection back alongside the trade records (Source: scripts/daily_reflection.py:1-80). The output is a structured reflection object consumable by later reasoning steps.

scripts/mt5_sync.py and scripts/binance_sync.py are typically scheduled more frequently (intra-day). Together they ensure the store has a near-real-time trade ledger. scripts/trade_adapter.py is invoked as the final transformation stage of each sync, validating fields, computing derived metrics, and rejecting malformed entries before they enter memory (Source: scripts/trade_adapter.py:40-60).

4. End-to-End Workflow

A typical operating cycle looks like this:

  1. The scheduled sync job (MT5 or Binance) pulls raw venue data.
  2. trade_adapter.py normalizes and validates each record.
  3. Records are written to the TradeMemory store and exposed by hosted/server.py.
  4. daily_reflection.py consumes the day's accumulated trades and publishes a reflection entry.
  5. Downstream agents query /memory/* or /agent/* to reason over the updated state.
flowchart LR
    A[MT5 Connector] --> D[trade_adapter.py]
    B[Binance Sync] --> D
    D --> E[(TradeMemory Store)]
    E --> F[hosted/server.py]
    E --> G[daily_reflection.py]
    F --> H[Clients / Agents]
    G --> H

The same MT5Connector powers both ad-hoc library usage and the scheduled sync path, so a single configuration (symbol, lookback bars, account credentials) governs live retrieval (Source: src/tradememory/mt5_connector.py:40-80). The hosted server, sync scripts, and reflection loop can be deployed independently or co-located; the only shared contract is the TradeMemory store schema, which trade_adapter.py enforces (Source: scripts/trade_adapter.py:1-60).

5. Practical Notes for Operators

  • Local terminal dependency: the MT5 path requires a running MetaTrader 5 terminal with API access enabled; the Binance path is purely HTTP.
  • Separation of concerns: connector code lives in src/tradememory/, while operational scripts live in scripts/. Keep this split when adding new venues.
  • Stateless hosted server: hosted/server.py is intended to be run behind a process manager (systemd, container orchestrator) that restarts on failure and flushes state on shutdown.
  • Reflection cadence: run daily_reflection.py after the final sync of the day so the reflection sees a complete trade set; running it mid-day can produce partial summaries.

Source: https://github.com/Eltano1985/tradememory-protocol / Human Manual

Doramagic Pitfall Log

Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.

high Security or permission risk requires verification

May increase setup, validation, or first-run risk for the user.

medium Capability evidence risk requires verification

May increase setup, validation, or first-run risk for the user.

medium Maintenance risk requires verification

May increase setup, validation, or first-run risk for the user.

medium Security or permission risk requires verification

May increase setup, validation, or first-run risk for the user.

Doramagic Pitfall Log

Found 7 structured pitfall item(s), including 1 high/blocking item(s). Top priority: Security or permission risk - Security or permission risk requires verification.

1. Security or permission risk: Security or permission risk requires verification

  • Severity: high
  • Finding: Project evidence flags a security or permission risk. Review the linked source before relying on this workflow.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: packet_text.keyword_scan | https://github.com/Eltano1985/tradememory-protocol

2. Capability evidence risk: Capability evidence risk requires verification

  • Severity: medium
  • Finding: README/documentation is current enough for a first validation pass.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: capability.assumptions | https://github.com/Eltano1985/tradememory-protocol

3. Maintenance risk: Maintenance risk requires verification

  • Severity: medium
  • Finding: Project evidence flags a maintenance risk. Review the linked source before relying on this workflow.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: evidence.maintainer_signals | https://github.com/Eltano1985/tradememory-protocol

4. Security or permission risk: Security or permission risk requires verification

  • Severity: medium
  • Finding: no_demo
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: downstream_validation.risk_items | https://github.com/Eltano1985/tradememory-protocol

5. Security or permission risk: Security or permission risk requires verification

  • Severity: medium
  • Finding: no_demo
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: risks.scoring_risks | https://github.com/Eltano1985/tradememory-protocol

6. Maintenance risk: Maintenance risk requires verification

  • Severity: low
  • Finding: issue_or_pr_quality=unknown。
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: evidence.maintainer_signals | https://github.com/Eltano1985/tradememory-protocol

7. Maintenance risk: Maintenance risk requires verification

  • Severity: low
  • Finding: release_recency=unknown。
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: evidence.maintainer_signals | https://github.com/Eltano1985/tradememory-protocol

Source: Doramagic discovery, validation, and Project Pack records

Community Discussion Evidence

These external discussion links are review inputs, not standalone proof that the project is production-ready.

Sources 1

Count of project-level external discussion links exposed on this manual page.

Use Review before install

Open the linked issues or discussions before treating the pack as ready for your environment.

Community Discussion Evidence

Doramagic exposes project-level community discussion separately from official documentation. Review these links before using tradememory-protocol with real data or production workflows.

Source: Project Pack community evidence and pitfall evidence