# How the Reflection and Memory System Tracks Trading Mistakes in TradingAgents-CN

> Discover how TradingAgents-CN uses reflection and memory to track trading mistakes. LLM analysis labels decisions, while vector embeddings store past errors for efficient retrieval.

- Repository: [hsliuping/TradingAgents-CN](https://github.com/hsliuping/tradingagents-cn)
- Tags: deep-dive
- Published: 2026-02-19

---

**TradingAgents-CN employs a dual-layer architecture where the `Reflector` component analyzes trading outcomes via LLM prompts to label decisions as correct or incorrect, while `FinancialSituationMemory` persists these analyses as vector embeddings alongside market contexts, enabling similarity-based retrieval of past errors.**

The TradingAgents-CN repository implements a sophisticated mistake-tracking pipeline that separates analytical reasoning from durable storage. Unlike hard-coded rule engines, this **reflection and memory system** uses large language models to interpret trading losses and vector databases to recall specific failure contexts when similar market conditions reappear.

## The Architecture: Separating Analysis from Storage

The system divides mistake tracking into two distinct responsibilities:

- **Analysis Layer**: The `Reflector` class in [`tradingagents/graph/reflection.py`](https://github.com/hsliuping/TradingAgents-CN/blob/main/tradingagents/graph/reflection.py) (lines 22-50) processes trading outcomes through LLM prompts to generate structured lessons.
- **Storage Layer**: The `FinancialSituationMemory` class in [`tradingagents/agents/utils/memory.py`](https://github.com/hsliuping/TradingAgents-CN/blob/main/tradingagents/agents/utils/memory.py) (lines 59-81) wraps a Chroma vector store to persist situation-reflection pairs as searchable embeddings.

This separation ensures that the logic for identifying mistakes (the reflection) remains decoupled from the mechanism for recalling them (the memory).

## How the Reflector Identifies and Analyzes Mistakes

### The Reflector Class and System Prompts

The `Reflector` uses a system prompt (lines 22-50 of [`reflection.py`](https://github.com/hsliuping/TradingAgents-CN/blob/main/reflection.py)) that instructs the LLM to evaluate each trading decision explicitly. The prompt requires the model to:

1. Label the decision as **correct** or **incorrect**
2. Enumerate contributing factors to the outcome
3. Generate a concise, actionable lesson

When a trade results in a loss, the LLM returns a reflection that explicitly marks the decision as *incorrect* and suggests corrective actions, such as reducing exposure during bearish regime shifts.

### Processing Losses as Mistake Triggers

The reflection pipeline triggers specifically on negative returns. In [`tradingagents/graph/trading_graph.py`](https://github.com/hsliuping/TradingAgents-CN/blob/main/tradingagents/graph/trading_graph.py), the `reflect_and_remember()` method (lines 77-93) passes the `returns_losses` parameter to the reflector. A negative value (e.g., `-0.043` for a 4.3% loss) signals to the LLM that the preceding decision requires critical analysis rather than positive reinforcement.

## How FinancialSituationMemory Persists Trading Lessons

### Storing Situation-Reflection Pairs

The `FinancialSituationMemory.add_situations()` method (lines 59-81 of [`memory.py`](https://github.com/hsliuping/TradingAgents-CN/blob/main/memory.py)) stores data as **pairs**: the raw market situation text alongside the LLM-generated reflection. Internally, this uses ChromaDB to create documents where:

- The **document content** is the market situation description
- The **metadata** contains the reflection (advice/lesson)

This structure ensures that the mistake analysis remains tethered to the specific market context that produced it.

### Vector-Based Retrieval of Past Mistakes

When the agent encounters new market conditions, `FinancialSituationMemory.get_memories()` queries the vector store using the current market description as the search vector. The system returns the most similar past situations—including those where mistakes occurred—along with their stored reflections.

This similarity search surfaces the *exact* scenario where a previous loss happened, together with the corrective recommendation generated by the LLM at that time, allowing the agent to avoid repeating the same error under analogous conditions.

## The Orchestration Pipeline in TradingGraph

The `TradingGraph` class in [`tradingagents/graph/trading_graph.py`](https://github.com/hsliuping/TradingAgents-CN/blob/main/tradingagents/graph/trading_graph.py) serves as the central conductor for mistake tracking. After each trade loop completes, the `reflect_and_remember()` method (lines 77-93) executes the following sequence:

1. **Extracts context**: Calls `_extract_current_situation()` to gather current market reports
2. **Invokes reflection**: Calls the five `reflect_*` methods of `Reflector` (for bull_memory, bear_memory, trader_memory, invest_judge_memory, and risk_manager_memory)
3. **Passes loss data**: Supplies the `returns_losses` value to signal whether the trade was a mistake
4. **Persists results**: Hands the resulting reflection strings to the appropriate memory instances via `add_situations()`

This orchestration ensures that every trading loss is automatically analyzed and archived without manual intervention.

## Code Examples: Tracking Mistakes in Practice

### Running Reflection After a Trade

```python

# Assume `tg` is an instance of TradingGraph that has just finished a trade

# `returns_losses` is the net P/L of the trade (negative = mistake)

tg.reflect_and_remember(returns_losses=-0.043)   # 4.3% loss

```

The `reflect_and_remember()` method calls the reflector for each agent role, ending with storage calls similar to:

```python
bull_memory.add_situations([(situation, result)])   # result = LLM reflection

```

### Inspecting Stored Mistakes

```python

# Retrieve the last 5 memories relevant to the current market snapshot

mems = tg.bull_memory.get_memories(current_situation, n_matches=5)

for m in mems:
    print("=== Past Situation ===")
    print(m["situation"])
    print("--- Reflection (advice) ---")
    print(m["recommendation"])          # the LLM‑generated mistake analysis

    print(f"Similarity: {m['similarity']:.2f}")

```

This retrieves the exact market description that previously led to a loss and the corrective advice generated at that time.

### End-to-End Example

```python
from tradingagents.graph.trading_graph import TradingGraph
from tradingagents.utils.logging_init import get_logger

logger = get_logger("demo")

# 1️⃣ Build a graph for a ticker

tg = TradingGraph(ticker="AAPL")

# 2️⃣ Run a single decision cycle (mocked)

tg.run_one_cycle()                     # populates tg.curr_state etc.

# 3️⃣ Simulate a loss and reflect

tg.reflect_and_remember(returns_losses=-0.075)   # 7.5% loss

# 4️⃣ Query memory to see what the system learned

past = tg.trader_memory.get_memories(tg.curr_state["market_report"], n_matches=1)
logger.info("Recall from memory:\n%s", past[0]["recommendation"])

```

This demonstrates the complete loop: **run → reflect → remember → recall**.

## Summary

- **TradingAgents-CN** implements a **reflection and memory system** that tracks trading mistakes through LLM analysis and vector storage.
- The **`Reflector`** class in [`tradingagents/graph/reflection.py`](https://github.com/hsliuping/TradingAgents-CN/blob/main/tradingagents/graph/reflection.py) uses system prompts to label decisions as correct or incorrect and generate corrective lessons when losses occur.
- **`FinancialSituationMemory`** in [`tradingagents/agents/utils/memory.py`](https://github.com/hsliuping/TradingAgents-CN/blob/main/tradingagents/agents/utils/memory.py) stores market situations alongside their reflections as vector embeddings, enabling semantic search.
- The **`TradingGraph.reflect_and_remember()`** method orchestrates the pipeline, automatically triggering reflection when `returns_losses` indicates a negative outcome.
- Future decisions retrieve similar past mistakes through **`get_memories()`**, allowing the system to avoid repeating errors under analogous market conditions.

## Frequently Asked Questions

### How does TradingAgents-CN determine if a trade was a mistake?

The system uses the **`returns_losses`** parameter passed to `reflect_and_remember()` in [`tradingagents/graph/trading_graph.py`](https://github.com/hsliuping/TradingAgents-CN/blob/main/tradingagents/graph/trading_graph.py). A negative value (e.g., `-0.05` for a 5% loss) signals that the preceding decision requires critical analysis. The `Reflector` class then uses an LLM prompt explicitly instructing the model to label the decision as **incorrect** and enumerate contributing factors.

### What information gets stored when a trading mistake occurs?

When a loss triggers reflection, `FinancialSituationMemory.add_situations()` stores a **pair** consisting of the raw market situation text and the LLM-generated reflection. According to [`tradingagents/agents/utils/memory.py`](https://github.com/hsliuping/TradingAgents-CN/blob/main/tradingagents/agents/utils/memory.py) (lines 59-81), this creates a vector embedding where the document content is the market description and the metadata contains the corrective advice, enabling later retrieval of both the context and the lesson.

### How does the system recall past mistakes during new trades?

The system queries stored reflections using `FinancialSituationMemory.get_memories()`, which performs a similarity search against the Chroma vector store. When the agent encounters new market conditions, it embeds the current situation description and retrieves the most similar past scenarios—including those where mistakes occurred—along with their stored reflections. This allows the agent to access specific corrective recommendations from analogous historical failures.

### Can the reflection system track mistakes for different trading roles separately?

Yes. The `TradingGraph.reflect_and_remember()` method (lines 77-93 of [`tradingagents/graph/trading_graph.py`](https://github.com/hsliuping/TradingAgents-CN/blob/main/tradingagents/graph/trading_graph.py)) maintains separate memory instances for distinct agent roles: `bull_memory`, `bear_memory`, `trader_memory`, `invest_judge_memory`, and `risk_manager_memory`. When processing a loss, the system calls the corresponding `reflect_*` method for each role, ensuring that specialized reflections (e.g., risk management mistakes vs. bullish trend misjudgments) are stored in their respective memory vectors for role-specific retrieval.