GuideOpen

Trader Memory Core (en)

Persistent state layer that tracks investment theses from screening idea to closed position with postmortem. Bundles screener, analysis, position sizing, and portfolio management outputs into a single thesis object per trade idea. {: .fs-6 .fw-300 }

Front matter
layout: default
title: "Trader Memory Core"
grand_parent: English
parent: Skill Guides
nav_order: 45
lang_peer: /ja/skills/trader-memory-core/
permalink: /en/skills/trader-memory-core/

Trader Memory Core

{: .no_toc }

Persistent state layer that tracks investment theses from screening idea to closed position with postmortem. Bundles screener, analysis, position sizing, and portfolio management outputs into a single thesis object per trade idea. {: .fs-6 .fw-300 }

<span class="badge badge-optional">FMP Optional</span>

Download Skill Package (.skill){: .btn .btn-primary .fs-5 .mb-4 .mb-md-0 .mr-2 } View Source on GitHub{: .btn .fs-5 .mb-4 .mb-md-0 }

<details open markdown="block"> <summary>Table of Contents</summary> {: .text-delta }

  • TOC

{:toc} </details>


1. Overview

Trader Memory Core answers the question: "What did I think, what happened, and what did I learn?" It provides a persistent, file-based state layer that follows each investment thesis through its entire lifecycle:

Screener Output → IDEA → ENTRY_READY → ACTIVE → PARTIALLY_CLOSED → CLOSED
IDEA / ENTRY_READY / ACTIVE / PARTIALLY_CLOSED → INVALIDATED

What it solves:

  • Eliminates the gap between screening and execution tracking
  • Provides a single source of truth for each trade idea across conversations
  • Enforces disciplined state transitions (no skipping steps)
  • Generates structured postmortem reports with P&L and MAE/MFE metrics
  • Schedules periodic reviews so no position is forgotten

Key capabilities:

  • 7 ingestion adapters: kanchi-dividend-sop, earnings-trade-analyzer, vcp-screener, pead-screener, canslim-screener, edge-candidate-agent, manual
  • Forward-only state machine with 6 statuses, including partial closes
  • Fingerprint-based deduplication (same screener output never registers twice)
  • Position sizing attachment from Position Sizer skill
  • Review scheduling with user-selected outcomes (OK, WARN, REVIEW)
  • Postmortem generation with optional MAE/MFE via FMP API

Phase 1 scope: Single-instrument equity and USD futures theses. Pair trades and options strategies are not supported.


2. When to Use

  • After a screener produces candidates and you want to track them persistently
  • When you want to transition a thesis from idea to entry-ready to active position
  • When attaching position-sizer output to size the trade
  • When checking which theses are due for review
  • When closing a position and generating a postmortem with lessons learned
  • When you want a trading journal with structured P&L statistics

Trigger phrases: "register thesis", "track this idea", "thesis status", "review due", "close position", "postmortem", "trading journal"


3. Prerequisites

  • Python 3.11–3.13 for this repository, with pyyaml and jsonschema (both in project dependencies)
  • FMP API key: Optional -- only needed for MAE/MFE calculation in postmortem reports. Core features (register, transition, close, review) work completely offline
  • State directory: state/theses/ is created automatically on first use
FMP API is only used for fetching daily price history to compute Maximum Adverse Excursion (MAE) and Maximum Favorable Excursion (MFE) during postmortem. If no API key is set, postmortem reports are still generated with all other fields.

{: .tip }


4. Quick Start

Run from the repository root after installing the skill dependencies. Python examples use an existing thesis: replace REPLACE_WITH_EXISTING_THESIS_ID with its ID and adjust report paths/dates before lifecycle updates. For the historical sequence below, the initial thesis history must start on or before March 15, 2026; history timestamps must remain chronological. The launcher forwards store/ingest/review arguments and uses uv run --project when uv is available.

# Step 1: Register screener output as thesis
python3 skills/trader-memory-core/scripts/trader_memory_cli.py ingest \
  --source kanchi-dividend-sop \
  --input reports/kanchi_entry_signals_2026-03-14.json \
  --state-dir state/theses/

# Step 2: Query your theses
python3 skills/trader-memory-core/scripts/trader_memory_cli.py store \
  --state-dir state/theses/ list --status IDEA

# Step 3: Generate summary statistics
python3 skills/trader-memory-core/scripts/trader_memory_cli.py review \
  --state-dir state/theses/ summary

5. Workflow

Step 1: Register -- Ingest screener output

Run the ingest script with the source screener name and its JSON output file:

# From kanchi-dividend-sop
python3 skills/trader-memory-core/scripts/trader_memory_cli.py ingest \
  --source kanchi-dividend-sop \
  --input reports/kanchi_entry_signals_2026-03-14.json \
  --state-dir state/theses/

# From earnings-trade-analyzer
python3 skills/trader-memory-core/scripts/trader_memory_cli.py ingest \
  --source earnings-trade-analyzer \
  --input reports/earnings_trade_scored_2026-03-14.json \
  --state-dir state/theses/

Each candidate in the JSON becomes an IDEA thesis. Registration is idempotent -- running the same input twice produces no duplicates (fingerprint-based dedup).

Supported sources: kanchi-dividend-sop, earnings-trade-analyzer, vcp-screener, pead-screener, canslim-screener, edge-candidate-agent, manual

Equity accounting is long-only. Do not ingest parabolic-short plans or record short-equity trades through manual; there is no adapter for those plans. Explicit SHORT directions are rejected before they can be discarded by raw registration, manual ingest, equity opening or shares-report attachment. Generic registration does not import a raw position: use validated futures attachment or open-position --contracts for futures LONG/SHORT.

When both initial prices are supplied, they must be finite numeric/non-bool values. Positive initial stop > positive entry is rejected at manual ingest, shares-report attachment and default equity activation (using the actual fill). Absent optional pairs and existing finite nonpositive-price behavior remain compatible. Do not apply this initial-entry rule to an ACTIVE/PARTIALLY_CLOSED long's stop: a profitable long may update its stop above original entry. Manual source prices remain provenance only; authoritative fills still come from open-position. For a backfill with a profit-protecting stop, open the long with its initial stop, then update the current stop after activation.

For a real long that gaps and fills below its planned stop, keep the default refusal unless explicitly acknowledging the actual fill with open-position --allow-gap-fill (API: allow_gap_fill=True). This opt-in only bypasses the positive fill-below-positive-stop geometry guard for equity; SHORT intent, invalid prices/quantities/state and all ingest/attachment validation still refuse. Futures reject this equity-only option. A normal/equal fill adds no gap annotation. The flag must be a Python bool in API calls. The acknowledgement still requires a share count: pass --shares or attach a sized position.

Preserve the target, planned stop, sizing audit fields and provenance. Store the actual fill and append a gap fill acknowledged entry to the protected ACTIVE status_history.reason, including exact actual fill and stop values. A supplied reason must remain a string. This audit survives later stop changes; inspect status history when reviewing the gap. Closing/trimming uses the actual fill for long-side P&L. This records a fill that already occurred, not approval to open a new trade or retain a breached stop. Planned sizing fields are not recalculated by this acknowledgement.

python3 skills/trader-memory-core/scripts/trader_memory_cli.py store \
  --state-dir state/theses/ open-position <id> \
  --actual-price 88 --actual-date 2026-11-01 --shares 10 \
  --allow-gap-fill --reason "record actual broker fill"

Explicit legacy short equity records (a SHORT word or a bare SELL, such as SELL_SHORT, Short position or SELL; labels such as Sell to close stay long) are refused before new accounting or MAE/MFE calculations. CLOSED/INVALIDATED legacy shorts can produce historical-only postmortems: P&L, MAE/MFE, position valuation and risk are shown as unavailable (—), with an explicit unsupported-short explanation. This report fetches no prices and leaves thesis/index state, stored outcomes and provenance unchanged; old values are not validated or corrected. ACTIVE/PARTIALLY_CLOSED records still cannot generate postmortems. They can still be marked reviewed or terminated as INVALIDATED without an exit price; these bookkeeping actions preserve all existing monetary fields and provenance. Summary statistics and monthly reports skip explicit shorts and report their excluded count (excluded_unsupported_equity_shorts in summary JSON when nonzero). Old manual provenance was free text: BUY, Long position and other non-short labels retain legacy long accounting. New direction inputs remain strictly LONG. Read-only inspection remains available; no old outcomes are migrated or re-signed. Ambiguous legacy records cannot be classified from a trailing stop alone. Keep short-equity journals external; never relabel one as a futures contract.

Step 2: Link analysis reports

After performing deeper analysis (US Stock Analysis, Technical Analyst, etc.), link the report to the thesis:

from pathlib import Path
import sys

sys.path.insert(0, str(Path("skills/trader-memory-core/scripts").resolve()))
from thesis_store import link_report

state_dir = Path("state/theses/")
thesis_id = "REPLACE_WITH_EXISTING_THESIS_ID"

link_report(state_dir, thesis_id,
            skill="us-stock-analysis",
            file="reports/us_stock_AAPL_2026-03-15.md",
            date="2026-03-15")

Step 3: Transition IDEA to ENTRY_READY

After validating the thesis with analysis, promote it:

from pathlib import Path
import sys

sys.path.insert(0, str(Path("skills/trader-memory-core/scripts").resolve()))
from thesis_store import transition

state_dir = Path("state/theses/")
thesis_id = "REPLACE_WITH_EXISTING_THESIS_ID"

transition(state_dir, thesis_id, "ENTRY_READY",
           reason="Technical confirmation: above 200-day MA with volume",
           event_date="2026-03-15T00:00:00+00:00")
transition() only allows IDEA → ENTRY_READY. All other transitions use dedicated functions.

{: .warning }

Step 4: Open position (ENTRY_READY to ACTIVE)

When you execute the trade, record the actual entry:

from pathlib import Path
import sys

sys.path.insert(0, str(Path("skills/trader-memory-core/scripts").resolve()))
from thesis_store import open_position

state_dir = Path("state/theses/")
thesis_id = "REPLACE_WITH_EXISTING_THESIS_ID"

open_position(state_dir, thesis_id,
              actual_price=155.50,
              actual_date="2026-03-16T10:30:00-04:00",
              shares=10,
              event_date="2026-03-16T10:30:00-04:00")

This is the only path to ACTIVE status. Requires both actual_price and actual_date (RFC 3339 format with timezone). An equity thesis also needs a quantity: pass shares, or run attach_position() (Step 5) while the thesis is still ENTRY_READY and omit shares. Without either, the call is rejected, because close() would otherwise record per-share P&L.

Step 5: Attach position sizing

Link the Position Sizer output to record how many shares and the risk parameters:

from pathlib import Path
import sys

sys.path.insert(0, str(Path("skills/trader-memory-core/scripts").resolve()))
from thesis_store import attach_position

state_dir = Path("state/theses/")
thesis_id = "REPLACE_WITH_EXISTING_THESIS_ID"

attach_position(state_dir, thesis_id,
                position_report_path="reports/position_sizer_AAPL_2026-03-16.json")

The report must have mode: "shares" (budget mode is rejected). Attaching on an ACTIVE thesis replaces the recorded quantity with the report's.

Step 6: Periodic review

Check which theses need attention:

python3 skills/trader-memory-core/scripts/trader_memory_cli.py review \
  --state-dir state/theses/ review-due --as-of 2026-04-15

Record a review with an explicitly chosen outcome:

from pathlib import Path
import sys

sys.path.insert(0, str(Path("skills/trader-memory-core/scripts").resolve()))
from thesis_store import mark_reviewed

state_dir = Path("state/theses/")
thesis_id = "REPLACE_WITH_EXISTING_THESIS_ID"

mark_reviewed(state_dir, thesis_id,
              review_date="2026-04-15",
              outcome="OK")  # OK, WARN, or REVIEW

The next_review_date is automatically advanced based on the review interval.

Step 7: Close and postmortem

When you exit the position:

from pathlib import Path
import sys

sys.path.insert(0, str(Path("skills/trader-memory-core/scripts").resolve()))
from thesis_store import close

state_dir = Path("state/theses/")
thesis_id = "REPLACE_WITH_EXISTING_THESIS_ID"

close(state_dir, thesis_id,
      exit_reason="target_hit",
      actual_price=172.00,
      actual_date="2026-05-01T15:45:00-04:00")

Then generate the postmortem:

python3 skills/trader-memory-core/scripts/trader_memory_cli.py review \
  --state-dir state/theses/ postmortem th_aapl_div_20260314_a3f1

The postmortem includes P&L, holding days, and (with FMP API key) MAE/MFE metrics. Output is saved to state/journal/pm_{thesis_id}.md.

Record the lessons learned on a CLOSED or INVALIDATED thesis, then re-run the postmortem to refresh the journal report:

python3 skills/trader-memory-core/scripts/trader_memory_cli.py store \
  --state-dir state/theses/ record-lessons th_aapl_div_20260314_a3f1 \
  --text "Sized too large into earnings; cut the position before the print."

Use --file PATH (UTF-8) for multi-line text. If a lesson already exists, pass --append or --replace. Lessons also appear under "Top Lessons" in review monthly-report.


Partial equity exits

Record a confirmed partial fill against an ACTIVE equity thesis. Set THESIS_ID to an existing thesis with sufficient remaining shares. A partial trim moves it to PARTIALLY_CLOSED; selling the entire remainder closes it. Final close adds to realized P&L from prior trims. --event-date can set the history timestamp when backfilling.

THESIS_ID="REPLACE_WITH_EXISTING_THESIS_ID"
python3 skills/trader-memory-core/scripts/trader_memory_cli.py store \
  --state-dir state/theses/ trim "$THESIS_ID" \
  --shares-sold 0.5 --price 160.00 --date 2026-04-20

Futures positions

Use a separate single-instrument thesis. Attach a verified futures-position-sizer SIZED report while it is IDEA or ENTRY_READY; an ACTIVE futures position cannot be re-attached. The report must contain a positive integer contract count, multiplier, LONG/SHORT direction, and USD currency. Transition the thesis to ENTRY_READY before recording a confirmed fill. This sequence assumes that prerequisite, a thesis history starting no later than the example entry date, and a matching SHORT report file. Set all dates to your actual fills; use --event-date to keep backfilled history chronological.

THESIS_ID="REPLACE_WITH_EXISTING_THESIS_ID"
python3 skills/trader-memory-core/scripts/trader_memory_cli.py store \
  --state-dir state/theses/ attach-futures-position "$THESIS_ID" \
  --report reports/futures_position_es.json
python3 skills/trader-memory-core/scripts/trader_memory_cli.py store \
  --state-dir state/theses/ open-position "$THESIS_ID" \
  --actual-price 5000 --actual-date 2026-05-10 --event-date 2026-05-10
python3 skills/trader-memory-core/scripts/trader_memory_cli.py store \
  --state-dir state/theses/ trim "$THESIS_ID" \
  --contracts-sold 1 --price 4950 --date 2026-05-12
python3 skills/trader-memory-core/scripts/trader_memory_cli.py store \
  --state-dir state/theses/ close "$THESIS_ID" \
  --exit-reason target_hit --actual-price 4900 --actual-date 2026-05-15

The example needs more than one original contract so the trim leaves a remainder. Close dispatches by asset type. Futures P&L uses price difference × multiplier × contracts × direction sign; non-USD contracts are rejected. For direct open without a report, supply --contracts, --multiplier, --direction, --contract-symbol, and --contract-currency USD.

CLI flag reference

FlagsPurpose
--source, --inputIngest source and input JSON
--state-dirLocal thesis state directory
--ticker, --status, --typeStore list filters
--reason, --event-dateTransition reason and history timestamp
--actual-price, --actual-date, --sharesConfirmed equity fill and entry quantity
--shares-sold, --contracts-sold, --price, --dateTrim quantity and fill price/date
--reportPosition sizing report to attach
--contracts, --multiplier, --directionDirect futures entry specification
--contract-symbol, --contract-currencyFutures identity and required USD currency
--exit-reason, --terminal-statusClose reason or terminate destination
--as-ofReview evaluation date

6. Understanding Output

Thesis YAML file

Each thesis is stored as a YAML file in state/theses/:

SectionKey FieldsDescription
Identitythesis_id, ticker, created_atUnique ID with ticker and hash
Classificationthesis_type, setup_type, catalyste.g., dividend_income, earnings_drift
Statusstatus, status_historyCurrent state + full transition log with timestamps
Entryentry.target_price, entry.actual_price, entry.actual_datePlanned vs actual entry
Exitexit.stop_loss, exit.target_price, exit.actual_pricePlanned vs actual exit
Positionposition.shares, position.risk_dollarsFrom Position Sizer attachment
Monitoringnext_review_date, review_historyReview schedule and past reviews
Originorigin.source_skill, origin.screening_gradeWhich screener and what score
Outcomeoutcome.pnl_pct, outcome.holding_daysComputed on close

Index file

state/theses/_index.json provides a lightweight lookup for fast queries without loading individual YAML files. It is rebuilt automatically and can be regenerated with rebuild_index().

Postmortem journal

state/journal/pm_{thesis_id}.md contains a structured markdown report with entry/exit summary, P&L analysis, MAE/MFE metrics (if available), and space for lessons learned.


7. Tips & Best Practices

  • Register early, decide later. Ingest all screener output as IDEAs. You can invalidate what you don't pursue.
  • Idempotency is your friend. Running the same ingest command twice is safe -- fingerprints prevent duplicates.
  • Use RFC 3339 dates. All date-time fields require timezone (e.g., 2026-03-16T10:30:00-04:00). Naive datetimes and space separators are rejected.
  • Invalidate rather than delete. Use terminate(state_dir, thesis_id, "INVALIDATED", exit_reason="thesis invalidated") instead of manually removing YAML files. This preserves the audit trail.
  • Review schedule matters. Default review interval is 30 days. Overdue theses surface via review-due, preventing forgotten positions.
  • Review outcomes. Choose OK, WARN, or REVIEW explicitly. Recording a review stores that outcome and advances the next review date; repeated WARN outcomes do not escalate automatically.
  • Link reports generously. The more analysis you cross-reference, the richer the postmortem.
  • Git-track state/. The state/ directory is designed to be committed, giving you a full audit trail with git log and git blame.
  • Postmortem without FMP. MAE/MFE are nice-to-have. P&L, holding days, and lessons learned work without any API.

8. Combining with Other Skills

SkillIntegration PointHow
kanchi-dividend-sopRegisterthesis_ingest.py --source kanchi-dividend-sop
earnings-trade-analyzerRegisterthesis_ingest.py --source earnings-trade-analyzer
vcp-screenerRegisterthesis_ingest.py --source vcp-screener
pead-screenerRegisterthesis_ingest.py --source pead-screener
canslim-screenerRegisterthesis_ingest.py --source canslim-screener
edge-candidate-agentRegisterthesis_ingest.py --source edge-candidate-agent
US Stock AnalysisLink reportlink_report(state_dir, thesis_id, skill="us-stock-analysis", file="reports/analysis.md", date="2026-03-15")
Technical AnalystLink reportlink_report(state_dir, thesis_id, skill="technical-analyst", file="reports/technical.md", date="2026-03-15")
Position SizerAttach sizingattach_position(state_dir, thesis_id, report_path)
Portfolio ManagerExecute tradesOpen/close positions, then update thesis
kanchi-dividend-review-monitorReview triggersT1-T5 anomaly detection feeds mark_reviewed()

9. Troubleshooting

ErrorCauseFix
ValidationError: ... is not a 'date-time'Date field missing timezone or using space separatorUse RFC 3339 format: 2026-03-16T10:30:00-04:00
ValueError: Cannot transition from terminal status CLOSEDAttempting to modify a closed/invalidated thesisTerminal statuses are permanent. Create a new thesis if needed.
ValueError: Use open_position() to transition to ACTIVECalled transition() with ACTIVE targetUse open_position(state_dir, thesis_id, actual_price, actual_date, shares=shares) instead
ValueError: open_position() requires a share count for an equity thesis ...Equity open with no shares and no share count from attach_position()Pass shares (CLI: --shares), or attach a position-sizer report while ENTRY_READY. Futures use --contracts or attach-futures-position.
store doctor exits 1The JSON report has "ok": false, or the state directory is missing or not a directory (ERROR: state directory not found or not a directory)Read the JSON report (missing_in_index, orphaned_in_index, field_mismatches, schema_errors); run rebuild-index for index drift
ValueError: Position report mode is 'budget', expected 'shares'. ...Position sizer report has mode: "budget"Re-run Position Sizer with --entry and --stop to get shares mode
ValueError: Missing required field: tickerScreener JSON missing expected fieldsCheck that the input matches the source adapter's expected format
Duplicate thesis not createdFingerprint matches existing thesisThis is intentional (idempotency). The existing thesis_id is returned.

10. Resources

References:

  • skills/trader-memory-core/references/thesis_lifecycle.md -- Status states and valid transitions
  • skills/trader-memory-core/references/field_mapping.md -- Source skill to canonical field mapping

Scripts:

  • skills/trader-memory-core/scripts/thesis_ingest.py -- Screener adapter registry and CLI
  • skills/trader-memory-core/scripts/thesis_store.py -- CRUD, transitions, and state management
  • skills/trader-memory-core/scripts/thesis_review.py -- Postmortem generation and summary statistics
  • skills/trader-memory-core/scripts/fmp_price_adapter.py -- FMP API integration for MAE/MFE

Schema:

  • skills/trader-memory-core/schemas/thesis.schema.json -- JSON Schema for thesis validation

Worked example:

  • examples/workflows/trade-memory-loop/sample-run-full-path/ -- End-to-end Plan -> Trade -> Record -> Postmortem -> Backtest -> Journal sample run

Source: https://github.com/tradermonty/claude-trading-skills/blob/main/docs/en/skills/trader-memory-core.md

Author: tradermonty, Trading skills. License: MIT.

Shown here with formatting for the web. Keep the author and license notice when you reuse it.

Related entries

There are more like this in the members library

The Claude Code library holds 13,843 entries. Members can search all of them by meaning and read every one in full.