AI and ML Integration

Intelligent Agent Memory System

MCP-based memory server for the genetic optimizer agent — three-tier hierarchy, sub-agent critic review, automatic rule synthesis, confidence-based forgetting, and screenshot-enhanced strategy generation.

⏱️ 10 min read📊 Level: Advanced

The Agent Memory System (api/agent_autopilot.py, ~1,320 lines) replaces flat last-N memory with a structured three-tier hierarchy exposed via a Model Context Protocol (MCP) server (api/mcp_memory_server.py). It enables the optimizer agent to retain proven rules across sessions, transfer knowledge between symbols, and provide the LLM with only relevant context — with a Memory Researcher fetching historical context and a Strategy Advisor generating recommendations.


Architecture Overview

Rendering diagram...

Key Components

ComponentFileLinesPurpose
Autopilot Loopapi/agent_autopilot.py745–1320Full orchestration: vision → memory research → strategy generation → block validation → backtest → learn → synthesize → evaluate → backtrack
MCP Serverapi/mcp_memory_server.py—TCP JSON-RPC server exposing search_agent_memory tool
Memory Researcherapi/agent_autopilot.py284–433Fetches rules + exact/cross-asset insights from MCP before strategy generation
Strategy Advisorapi/agent_autopilot.py436–676Two-turn LLM dialogue: turn 0 selects tags for memory search, turn 1 analyzes context and writes recommendations
Critic Sub-Agentapi/agent_autopilot.py679–742Standalone strategy logic validator (bypassed in autopilot loop; available for external use)
Block Validationapi/agent_autopilot.py903–937Programmatic check for restricted blocks (pro_only, kline_only)
Rule Synthesisapi/agent_autopilot.py110–202Promotes 3+ similar insights into a permanent rule
Lifecycle Evaluationapi/agent_autopilot.py205–270Reinforces success, decays/deprecates failures
Tag Classificationapi/agent_autopilot.py27–107LLM assigns tags, strategy type, outcome to each insight

Database Model

Sources:

The table is auto-created at startup (api/depthsight_api.py:1262). Extended fields (tags, symbol, strategy_type, outcome, confidence, validated_count, config_hash) were added via migration alembic/versions/2a487db2c451_add_memory_tags.py.

Memory Types

TypeTTLDescription
rulePermanentCross-asset rules promoted from insights
strategy_insight90/30/60 daysTagged conclusions from backtest runs
observation7 daysRaw ephemeral results
preferenceN/AUser-level preferences
market_contextN/AMarket regime observations

TTL Policies for Insights

OutcomeTTL
Success (PnL > 0, trades >= 5)90 days
Failure30 days
Optimization result60 days
RulesPermanent (expires_at = None)

MCP Memory Server

The memory system is exposed as a Model Context Protocol tool via a custom TCP-based JSON-RPC 2.0 server (api/mcp_memory_server.py, 329 lines).

Protocol

AspectDetail
TransportTCP (not stdio)
ProtocolJSON-RPC 2.0
Port8100 (configurable via MCP_MEMORY_PORT)
Host127.0.0.1 (dev) / 0.0.0.0 (Docker)
Version2025-03-26

Tool: search_agent_memory

Sources:

Context Format

### Agent Memory Context

**Universal Rules:**
- 🔴 [conf: 85%] Volume spike > 2x required for breakout

**ETHUSDT Insights:**
- 🟡 [SUCCESS, PnL: +15%] Ascending triangle breakout with ADX confirmation

**Cross-Asset Transfer:**
- ⚡ [Transfer from BTCUSDT] [SUCCESS] Similar momentum setup

Deployment

In Docker, the MCP server runs as a separate container:

Sources:

Other services (api, websocket, bot, celery_worker) connect via MCP_MEMORY_HOST=mcp-memory.

Environment Variables

VariableDefaultDescription
MCP_MEMORY_PORT8100TCP port
MCP_MEMORY_HOST127.0.0.1Host (use 0.0.0.0 in Docker)
AI_ADVISOR_MODEL—Model for Strategy Advisor agent (defaults to AI_CRITIC_MODEL)
MAX_AUTOPILOT_ITERATIONS5Max iterations for the autopilot loop

Sub-Agent Critic

The Critic sub-agent (api/agent_autopilot.py:679-742) is a standalone LLM validator that checks strategy JSON for logical flaws. It is bypassed in the autopilot loop (replaced by Memory Researcher + Strategy Advisor) but available as a direct API or utility function.

Critic Checklist

The critic (api/prompts/critic_system.md) checks for:

CheckDescription
Inverted SL/TPStop Loss above entry for long, or Take Profit below
Contradictory filtersBoth uptrend AND downtrend conditions simultaneously
Missing weightsZero or missing foundation weights
Missing partial exitsStrategy defines exits but no partial exit rules

Output Format

{"approved": true}

On rejection:

{"approved": false, "reason": "Stop Loss is set above entry price for long position.", "critical_flaw": "inverted_stop_loss"}
Sources:

Model Selection

Configurable via AI_CRITIC_MODEL env var:

ProviderDefault Model
Geminigemini-3-flash-preview
Qwenqwen-max
OpenRoutergoogle/gemini-3-flash-preview

Auto-Approve Fallback

If the critic LLM call fails entirely (timeout or JSON decode), the system auto-approves the strategy to avoid blocking the pipeline:

{"approved": True, "reason": "Auto-approved (critic error)"}

Memory Researcher

Before strategy generation, the Memory Researcher (api/agent_autopilot.py:284-433) queries the MCP server for relevant historical context — fetching active rules, exact-symbol insights, and cross-asset transfers.

Sources:

The context is formatted as a structured text block with three sections:

**Universal Rules (max 2):**
- [conf: 85%] Volume spike > 2x required for breakout

**Exact Insights for {symbol} (max 3):**
- [SUCCESS, PnL: +15%] Ascending triangle breakout with ADX

**Cross-Asset Transfer:**
- [Transfer from BTCUSDT] [SUCCESS] Similar momentum setup

Strategy Advisor

After the Memory Researcher returns context, the Strategy Advisor (api/agent_autopilot.py:436-676) conducts a two-turn LLM dialogue:

  1. Turn 0 — Tag Selection: The advisor proposes tags for memory search (e.g., ["momentum", "breakout", "ethusdt"]). These tags are used to query additional context.
  2. Turn 1 — Recommendation: The advisor analyzes the full context (tags + memory + chart screenshot on 1st iteration) and writes a strategy recommendation.
Sources:

Configurable via AI_ADVISOR_MODEL env var (default: same as AI_CRITIC_MODEL).


Block Validation

After strategy generation, a programmatic block validator (api/agent_autopilot.py:903-937) checks for restricted blocks:

Block TypeRestriction
pro_onlyOnly allowed if user has Pro subscription
kline_onlyOnly allowed on supported timeframes

If validation fails, the autopilot retries strategy generation with the list of violating blocks as feedback.


Autopilot Loop

The full agent cycle is orchestrated in run_autopilot_loop() (api/agent_autopilot.py:745-1135). It accepts a max_iterations parameter (default: MAX_AUTOPILOT_ITERATIONS):

Sources:
Rendering diagram...

Loop Steps

StepDescription
VisionSeparate LLM call analyzes chart screenshot (1st iteration only); returns pattern description used as context
Memory ResearchFetch rules + exact/cross-asset insights via MCP
Strategy AdvisorTwo-turn LLM: selects tags → generates strategy with full context
Block ValidationProgrammatic check for pro_only / kline_only violations; retries on failure
BacktestCelery task executes the backtest asynchronously
LearnSave insight with tags, outcome, confidence; success = 90d TTL, failure = 30d TTL
SynthesizeIf 3+ insights for this strategy type, promote to a rule
EvaluateReinforce success (+0.1 confidence) or decay failure (-0.2); deprecate if confidence <= 0.3
BacktrackCompare PnL to best so far; reset strategy if worse, update baseline if better

Screenshot & Vision Analysis

On the first autopilot iteration, a chart screenshot is sent to the LLM in two stages:

  1. Vision analysis — a separate LLM call analyzes the screenshot for chart patterns, returning structured observations
  2. Strategy generation — the vision output is passed as context to the Strategy Advisor
Sources:

The feature is optional — both image_base64 and image_mime_type are nullable parameters.


Rule Lifecycle: Reinforcement & Forgetting

Two mechanisms control memory decay:

1. TTL-Based Forgetting

Each memory has an expires_at timestamp. Expired rows are:

  • Filtered out of all queries (expires_at IS NULL OR expires_at > now())
  • Purged by delete_expired_memories() CRUD function

2. Confidence-Based Deprecation

Sources:
EventEffect
Backtest confirms ruleconfidence += 0.1, validated_count += 1
Backtest contradicts ruleconfidence -= 0.2, validated_count -= 1
Confidence <= 0.3Rule marked deprecated (expires_at = now())
validated_count <= -2Rule marked deprecated

Rule Promotion (Synthesis)

When 3+ insights with the same strategy type exist, the system promotes them into a permanent rule:

Sources:

MCP Integration with AI Providers

The AI Assistant (api/ai_assistant.py) converts MCP tools into each provider's native function-calling format:

Sources:
ProviderMechanismConfiguration
Geminitypes.Tool with FunctionCallingConfig(mode="ANY")Forces function call on turn 0, JSON response on subsequent turns
OpenRouter / QwenOpenRouter function-calling formatDetects native tool_calls or text-fallback regex call:search_agent_memory(...)
FallbackRegex call:search_agent_memory(...)For models that don't support native function calling

The user_id is injected server-side into every MCP tool call, so the model does not need to supply it.


Tag Classification

Tags are assigned by an LLM call at insight save time (tag_strategy_insight()):

Sources:

The prompt (api/prompts/tag_insight.md) instructs the LLM to:

  1. Extract the strategy type from structural blocks
  2. Prefer reusing existing tags for consistency
  3. Assign confidence based on PnL and trade count
  4. Return JSON with strategy_type, tags, outcome, confidence

If the LLM call fails, the system falls back to extracting strategy_type from block names and building tags from [symbol, strategy_type, filter types].


REST API

In addition to the MCP interface, memories can be managed via REST:

Sources:

Why This Wins

Judge CriteriaWhat We Show
Memory AgentThree-tier hierarchy with MCP tool interface
Persistent MemoryLives in PostgreSQL across sessions
Learning from ExperienceRules auto-extracted from 3+ similar insights
ForgettingTTL expiry + confidence-based deprecation
Transfer LearningKnowledge from ETH applied to BTC, marked ⚡
Memory ResearcherFetches rules + insights for strategic context before generation
Strategy AdvisorTwo-turn LLM dialogue: selects tags → generates strategy
Screenshot VisionSeparate vision analysis step on first generation pass
MCP ProtocolStandardized tool interface compatible with any MCP host