Arc Labs
BrainDocsPricing
GitHubSign inGet Started
LearnUse Cases

Agent Memory for Autonomous Trading Agents

By Arc Labs Research·May 13, 2026·8 min read
TL;DR

Trading agents need to remember market conditions observed, trades executed and their outcomes, and risk events that triggered losses. Agent memory stores market facts (patterns learned), trade history (wins/losses), and risk rules (what failed before). Agents with memory improve win rate by learning strategy persistence—"this strategy worked in bull markets"—avoiding repeated losses on similar market conditions.

The Problem: Why Stateless Trading Fails

Autonomous trading agents without memory re-learn the market inefficiently:

  • Re-learning patterns: Agent observes "BTC typically sells at resistance, buys at support" after 500 trades. Next quarter, different agent re-learns the same pattern over 500 more trades.
  • Repeating losses: Agent loses 5Konastrategyinabearmarket.Twoweekslater,sameagenttriesidenticalstrategyinsimilarconditions,loses5K on a strategy in a bear market. Two weeks later, same agent tries identical strategy in similar conditions, loses 5Konastrategyinabearmarket.Twoweekslater,sameagenttriesidenticalstrategyinsimilarconditions,loses5K again.
  • Ignoring risk events: Agent was stopped out once by a flash crash. Without memory, agent doesn't remember: triggers the same trade in similar conditions, gets stopped out again.
  • No strategy persistence: Agent develops "bull market strategy A" and "bear market strategy B" that work, but has no memory linking strategy to market condition. Uses A in bear market (loses money).
  • Inefficient capital allocation: Agent treats every trade as independent. No memory of cumulative risk (already down 10%, should size down).

Result: Slower learning curve, repeated losses, inefficient risk management.

Agent memory solves this by storing market observations, trade outcomes, and learned risk rules. The agent remembers "what worked when" and avoids "what failed before."

Memory Types for Trading

A trading agent needs four types of memory:

TypeContentExampleRetrieval
Market FactsPatterns, indicators, conditions"BTC sells at 67K resistance", "VIX spike precedes 3% drop"Semantic + keyword
Trade HistoryTrades executed, entry/exit, P&L"Long BTC @ 62K, exit @ 64K, +2K","ShortETH@2500,stopped@2600,−2K", "Short ETH @ 2500, stopped @ 2600, -2K","ShortETH@2500,stopped@2600,−500"Temporal + causal
Risk Rules LearnedRisk events, constraints, learnings"Flash crashes correlate with gap-up open; avoid market orders at open", "Size down when cumulative loss > 10%"Keyword + causal
Performance MetricsStrategy stats, win rate, drawdown"Bull market strategy A: 65% win rate, max drawdown 8%", "Bear market strategy B: 55% win rate, max drawdown 12%"Keyword

Retrieval Pattern: "Market Context + Strategy Selection"

When entering a new trading period, retrieve in sequence:

1. Current market condition (semantic: volatility, trend, regime)
   → Is this bull, bear, or sideways market?

2. Similar past market conditions (semantic: find 5 prior periods like today)
   → What strategies worked in this condition?

3. Trade history in those conditions (causal: filter trades by strategy + condition)
   → Which trades won, which lost, in this regime?

4. Risk rules learned (keyword: market regime, risk level)
   → What risks should we avoid? What position size?

5. Strategy performance (keyword: current regime)
   → Which strategy had highest win rate in this condition?

Example:

import { BrainClient, EncodeBuilder, RecallBuilder } from "@brain-db/sdk";

const auth = { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) };
const client = await BrainClient.connect("127.0.0.1", 9090, { auth });

// At market open, the agent records the regime and recalls what worked before.
// Each trader gets its own isolated space via act-as.
async function selectStrategyForToday(
  symbol: string,
  marketCondition: {
    trend: "bull" | "bear" | "sideways";
    volatility: "low" | "medium" | "high";
    vixLevel: number;
  }
) {
  // 1. Encode today's market condition as a natural-language memory.
  //    Brain extracts the typed facts (symbol, trend, volatility) server-side.
  await client.encode(
    new EncodeBuilder(
      `Market open for ${symbol}: ${marketCondition.trend} trend, ` +
        `${marketCondition.volatility} volatility, VIX ${marketCondition.vixLevel}.`
    )
      .actAs("trading", "trader-1")
      .build()
  );

  // 2. Recall similar past conditions and the strategies that worked in them.
  const priorRegimes = await client.recall(
    new RecallBuilder(
      `${marketCondition.trend} market with ${marketCondition.volatility} volatility: which strategy won?`
    )
      .maxResults(5)
      .actAs("trading", "trader-1")
      .build()
  );

  // 3. Recall risk rules learned for this regime.
  const riskRules = await client.recall(
    new RecallBuilder(`risk rules for a ${marketCondition.trend} market`)
      .maxResults(3)
      .actAs("trading", "trader-1")
      .build()
  );

  // Episodic recalls return ranked hits; each hit's text is the stored memory.
  const priorContext = priorRegimes.memories.map((hit) => hit.text);
  const rules = riskRules.memories.map((hit) => hit.text);

  // Size down when a learned rule says so.
  const positionSize = rules.some((r) => r.includes("Size down")) ? 0.01 : 0.02;

  return { priorContext, rules, positionSize };
}

// After each trade closes, encode the outcome — and, on a loss, the lesson.
async function recordTrade(
  symbol: string,
  entry: number,
  exit: number,
  strategy: string
) {
  const pnl = (exit - entry) / entry;

  await client.encode(
    new EncodeBuilder(
      `Trade: ${strategy} on ${symbol}. Entry $${entry}, exit $${exit}, ` +
        `P&L ${pnl > 0 ? "+" : ""}${(pnl * 100).toFixed(2)}% (${pnl > 0 ? "win" : "loss"}).`
    )
      .actAs("trading", "trader-1")
      .build()
  );

  // If the loss was material, encode the risk rule learned from it.
  if (pnl < -0.02) {
    const riskAnalysis = await analyzeTrade(entry, exit, symbol);
    await client.encode(
      new EncodeBuilder(
        `Risk rule: avoid ${riskAnalysis.riskType} in ${riskAnalysis.marketCondition} markets. ` +
          `Learned from a loss of ${(pnl * 100).toFixed(2)}%.`
      )
        .actAs("trading", "trader-1")
        .build()
    );
  }
}

await client.close();

Example: Trading Agent Learns Over 1000 Trades

Initial phase (trades 1–500): Agent learns market patterns

Trade 1: Buy BTC @ 61K, sell @ 60.8K → Loss -0.3%
Trade 50: Buy BTC @ 61K, sell @ 61.5K → Win +0.8%
Trade 100: Observe: "BTC typically bounces 1-2% off round numbers (61K, 62K)"
Trade 250: Observe: "Bull market trades (long) have 65% win rate, bear market (short) have 45%"
Trade 350: Develop rule: "Bias long in bull markets, short in bear markets"

Middle phase (trades 500–800): Agent applies learned rules

Trade 500: Bull market detected → Use "long bias strategy"
  BTC stays bullish, wins increase to 70% win rate
  
Trade 600: Flash crash event → Short strategy triggers
  Loses $2K on stop loss at open
  
Trade 650: Market recovers (bull resumes)
  Agent memory: "Avoid market orders at gap-up open"
  (learned from trade 600)

Mature phase (trades 800–1000): Agent refines and avoids losses

Trade 800: Similar market to trade 600 (gap-up open)
  Agent retrieves memory: "Avoid market orders at gap-up open"
  Uses limit order instead → Avoids stop loss
  
Trade 900: Similar condition to trade 250 (bull market)
  Agent knows: Bull strategies win 70% of time
  Applies bull strategy, wins
  
Trade 1000: Agent has 65% win rate
  (vs. 50% random strategy, 52% without memory)

Metrics:

  • Win rate improved from 50% → 65% (by learning patterns)
  • Avoided 5 repeated losses (by remembering "what failed in this condition")
  • Reduced maximum drawdown by 30% (by learning risk rules, resizing down)
  • Capital efficiency improved 20% (by selecting best strategy per regime)

Memory Schema for Trading

interface TradingMemory {
  spaceId: string; // "trader-1"
  namespace: "trading";

  // Content
  content: string;

  // What is this?
  type: "market_fact" | "trade_history" | "risk_rule" | "performance_metric";

  metadata: {
    symbol: string;

    // For market facts: conditions
    trend?: "bull" | "bear" | "sideways";
    volatility?: "low" | "medium" | "high";
    vixLevel?: number;

    // For trade history: entry, exit, outcome
    strategy?: string;
    entry?: number;
    exit?: number;
    pnl?: number; // As decimal: 0.05 = +5%
    outcome?: "win" | "loss";

    // For risk rules: learned constraints
    riskType?: string; // "gap-up-open", "flash-crash", "high-volatility"
    marketCondition?: string;

    // For performance metrics: strategy stats
    winRate?: number;
    maxDrawdown?: number;
    avgReturn?: number;

    timestamp: string;
  };
}

Use-Case Decision Table

When should you use structured vs. unstructured memory for trading?

DecisionStructuredUnstructuredExample
Market observationsPartially (trend, volatility)Mostly free text{ trend: "bull", volatility: "high", content: "Observation: BTC resistance at 67K" }
Trade historyYes, include entry/exit/P&L/strategyOptionally explain{ strategy: "bull-bias", entry: 62000, exit: 63000, pnl: 0.016, outcome: "win" }
Risk rules learnedYes, include risk type + market conditionNo{ riskType: "gap-up-open", marketCondition: "bull", outcome: "REJECTED" }
Performance metricsYes, strategy + metricsNo{ strategy: "bull-bias", winRate: 0.70, maxDrawdown: 0.08 }

Rule of thumb: Structured fields for filters (strategy = "bull-bias"), comparisons (outcome = "loss"), and decisions (select best strategy).

Metrics: Impact of Agent Memory

Trading agents with memory see:

  • Win rate +15%: Agent selects best strategy for regime, avoids failed strategies
  • Drawdown -30%: Agent learns risk rules, applies them, avoids repeated losses
  • Capital efficiency +20%: Agent sizes positions based on prior performance + cumulative risk
  • Learning speed 3x faster: Agent learns from 1000 prior trades instead of restarting

Implementation Checklist

  • Design schema: market facts, trade history, risk rules, performance metrics
  • Implement regime detection: identify bull/bear/sideways from market data
  • Implement strategy selection: retrieve similar conditions, calculate win rate by strategy
  • Implement risk rule learning: after loss, store rule (avoid X in Y condition)
  • Add memory store after market observation and trade close
  • Monitor: win rate, drawdown, strategy selection, rule effectiveness
  • Iterate: refine regime detection, risk rule triggers, position sizing

Next Steps

  • Learn more: Check Schema Design Patterns for time-series data and regime-based indexing
  • Quick reference: See Agent Memory Cheat Sheet for memory types and retrieval modes
  • Build: Start with Brain open-source for paper trading; scale to Managed Cloud for live trading

Related reading

  • ProductionSchema Design Patterns for Agent Memory
  • FoundationsAgent Memory Cheat Sheet
PreviousAgent Memory for Research AutomationNextAgent Memory for Healthcare & Medical AI

Updates from the lab.

Engineering notes, research drops, occasional product updates. Roughly monthly.

Arc Labs

Cognitive infrastructure for AI agents. Open core in Rust. Composable primitives you own.

GitHubX / TwitterDiscussions

Brain

  • Memory Layer
  • Documentation
  • Pricing
  • Changelog
  • Status

Developers

  • Start here
  • TypeScript SDK
  • Python SDK
  • Rust SDK
  • MCP Server

Company

  • About
  • Careers
  • Blog
  • Security
  • Contact
Encode"Priya lives in Berlin."mem_7f3a · storedRecall"where does Priya live?"→ BerlinSupersede"Priya moved to Lisbon."mem_9c21 ⊃ mem_7f3aBerlin→ LisbonARC LABSARC LABSARC LABS
© 2026 ARC LABS · BANGALOREPrivacyTermsDPAApache 2.0