TradeMemory API Reference

February 23, 2026 · View on GitHub

TradeMemory exposes its functionality via HTTP endpoints. Any MCP-compatible AI agent or HTTP client can use these endpoints.

Base URL: http://localhost:8000


Implemented Tools

Trade Journal

POST /trade/record_decision

Record a trade entry decision with full context.

Request body:

ParameterTypeRequiredDescription
trade_idstringyesUnique trade ID (format: T-YYYY-NNNN)
symbolstringyesTrading instrument (e.g. XAUUSD)
directionstringyes"long" or "short"
lot_sizefloatyesPosition size
strategystringyesStrategy tag (e.g. VolBreakout)
confidencefloatyesAgent confidence score, 0.0-1.0
reasoningstringyesNatural language explanation of why
market_contextobjectyesSee MarketContext
referencesstring[]noPast trade IDs referenced (default: [])

Response:

{
  "success": true,
  "trade_id": "T-2026-0251",
  "timestamp": "2026-02-23T09:03:42+00:00"
}

Errors:

  • 400 — Invalid confidence (not 0.0-1.0), invalid direction, or database write failure.

Example (Python):

import requests

resp = requests.post("http://localhost:8000/trade/record_decision", json={
    "trade_id": "T-2026-0251",
    "symbol": "XAUUSD",
    "direction": "long",
    "lot_size": 0.05,
    "strategy": "VolBreakout",
    "confidence": 0.72,
    "reasoning": "London open breakout above 2890 with volume confirmation.",
    "market_context": {
        "price": 2891.50,
        "session": "london",
        "atr": 28.3,
        "indicators": {"rsi_14": 58.2}
    },
    "references": ["T-2026-0247"]
})

data = resp.json()
print(data["trade_id"])   # T-2026-0251
print(data["timestamp"])  # 2026-02-23T09:03:42+00:00

POST /trade/record_outcome

Record the outcome of a trade after it closes.

Request body:

ParameterTypeRequiredDescription
trade_idstringyesID of the trade to update
exit_pricefloatyesPrice at exit
pnlfloatyesRealized P&L in account currency
exit_reasoningstringyesWhy the agent exited
pnl_rfloatnoP&L in R-multiples
hold_durationintnoMinutes the position was held
slippagefloatnoEntry slippage in pips
execution_qualityfloatno0.0-1.0 score
lessonsstringnoWhat was learned from this trade

Response:

{
  "success": true,
  "trade_id": "T-2026-0251"
}

Errors:

  • 400 — Trade ID not found, invalid execution_quality (not 0.0-1.0), or database write failure.

Example (Python):

resp = requests.post("http://localhost:8000/trade/record_outcome", json={
    "trade_id": "T-2026-0251",
    "exit_price": 2897.20,
    "pnl": 28.50,
    "pnl_r": 2.1,
    "exit_reasoning": "Hit 2R target at 2897.",
    "hold_duration": 87,
    "slippage": 0.3,
    "execution_quality": 0.88,
    "lessons": "Volume confirmation at London open continues to work."
})

POST /trade/query_history

Search past trades by strategy, symbol, or both.

Request body:

ParameterTypeRequiredDescription
strategystringnoFilter by strategy name
symbolstringnoFilter by trading instrument
limitintnoMax results (default: 100)

Response:

{
  "success": true,
  "count": 2,
  "trades": [
    {
      "id": "T-2026-0251",
      "timestamp": "2026-02-23T09:03:42+00:00",
      "symbol": "XAUUSD",
      "direction": "long",
      "strategy": "VolBreakout",
      "confidence": 0.72,
      "pnl": 28.50,
      "pnl_r": 2.1
    }
  ]
}

Trades are returned ordered by timestamp DESC (newest first). Each trade object contains all TradeRecord fields — see SCHEMA.md for the full structure.

Example (Python):

# Get all VolBreakout trades
resp = requests.post("http://localhost:8000/trade/query_history", json={
    "strategy": "VolBreakout",
    "limit": 50
})

trades = resp.json()["trades"]
win_rate = sum(1 for t in trades if t["pnl"] and t["pnl"] > 0) / len(trades)
print(f"VolBreakout win rate: {win_rate:.0%}")

GET /trade/get_active

Get all currently open positions (trades with no recorded outcome).

Parameters: None.

Response:

{
  "success": true,
  "count": 1,
  "trades": [
    {
      "id": "T-2026-0253",
      "timestamp": "2026-02-23T14:22:10+00:00",
      "symbol": "XAUUSD",
      "direction": "long",
      "lot_size": 0.05,
      "strategy": "VolBreakout",
      "confidence": 0.85,
      "reasoning": "...",
      "pnl": null,
      "exit_timestamp": null
    }
  ]
}

Example (Python):

resp = requests.get("http://localhost:8000/trade/get_active")
active = resp.json()["trades"]
print(f"{len(active)} open positions")

Reflection

POST /reflect/run_daily

Generate a daily reflection summary. Uses LLM (Claude) if ANTHROPIC_API_KEY is set, otherwise falls back to rule-based analysis.

Query parameters:

ParameterTypeRequiredDescription
datestringnoTarget date as YYYY-MM-DD (default: today)

Response:

{
  "success": true,
  "date": "2026-02-23",
  "summary": "=== DAILY SUMMARY: 2026-02-23 ===\n\nPERFORMANCE:\n..."
}

The summary field contains a markdown-formatted reflection report. See REFLECTION_FORMAT.md for the full template.

Example (Python):

# Today's reflection
resp = requests.post("http://localhost:8000/reflect/run_daily")
print(resp.json()["summary"])

# Specific date
resp = requests.post("http://localhost:8000/reflect/run_daily?date=2026-02-22")

State Management

POST /state/load

Load agent state at session start. Creates a new empty state if the agent has no saved state.

Request body:

ParameterTypeRequiredDescription
agent_idstringyesUnique agent identifier

Response:

{
  "success": true,
  "state": {
    "agent_id": "ng_gold_v1",
    "last_active": "2026-02-23T08:45:12+00:00",
    "warm_memory": {
      "last_mt5_sync_timestamp": "2026-02-23T08:40:00+00:00"
    },
    "active_positions": ["T-2026-0250"],
    "risk_constraints": {
      "asian_max_lot": 0.025,
      "london_max_lot": 0.08
    }
  }
}

Example (Python):

resp = requests.post("http://localhost:8000/state/load", json={
    "agent_id": "ng_gold_v1"
})

state = resp.json()["state"]
constraints = state["risk_constraints"]
insights = state["warm_memory"]

POST /state/save

Persist current agent state. Automatically updates last_active timestamp.

Request body:

ParameterTypeRequiredDescription
stateobjectyesFull SessionState object

The state object must contain:

FieldTypeDescription
agent_idstringAgent identifier
last_activestringISO 8601 timestamp (auto-updated on save)
warm_memoryobjectL2 insights as key-value pairs
active_positionsstring[]List of open trade IDs
risk_constraintsobjectDynamic risk parameters

Response:

{
  "success": true,
  "agent_id": "ng_gold_v1"
}

Example (Python):

resp = requests.post("http://localhost:8000/state/save", json={
    "state": {
        "agent_id": "ng_gold_v1",
        "last_active": "2026-02-23T12:00:00+00:00",
        "warm_memory": {"session_bias": "london_bullish"},
        "active_positions": [],
        "risk_constraints": {"max_lot": 0.05}
    }
})

MT5 Integration

POST /mt5/connect

Connect to a MetaTrader 5 account. Requires the MetaTrader5 Python package (Windows only).

Request body:

ParameterTypeRequiredDescription
loginintyesMT5 account number
passwordstringyesAccount password
serverstringyesBroker server name
pathstringnoPath to MT5 terminal executable

Response:

{
  "success": true,
  "message": "Connected to MT5"
}

Errors:

  • 400MetaTrader5 package not installed, or connection failed.

POST /mt5/sync

Sync closed trades from MT5 to TradeJournal. Groups MT5 deals by position, determines entry/exit, and records both decision and outcome.

Query parameters:

ParameterTypeRequiredDescription
agent_idstringnoAgent ID for state tracking (default: ng-gold-agent)

Response:

{
  "success": true,
  "agent_id": "ng-gold-agent",
  "stats": {
    "synced": 3,
    "skipped": 1,
    "errors": 0
  }
}

Health Check

GET /health

Response:

{
  "status": "healthy",
  "service": "TradeMemory Protocol",
  "version": "0.1.0"
}

Not Yet Implemented (Phase 2)

These tools are planned but not yet available:

ToolPurpose
reflect.run_weeklyWeekly deep reflection with strategy-level analysis
reflect.get_insightsRetrieve curated L2 insights
reflect.query_patternsAsk specific questions about discovered patterns
risk.get_constraintsGet current dynamic risk parameters
risk.check_tradeValidate a proposed trade against active constraints
risk.get_performanceGet aggregated performance metrics
risk.overrideHuman override of risk parameters (requires auth)
state.get_identityGet agent identity and personality context
state.heartbeatKeep-alive signal for long-running agents

Data Types

MarketContext

FieldTypeRequiredDescription
pricefloatyesCurrent/entry price
atrfloatnoAverage True Range
sessionstringno"asian", "london", or "newyork"
indicatorsobjectnoKey-value pairs of indicator values
news_sentimentfloatno-1.0 (bearish) to 1.0 (bullish)

Error Response

All errors return HTTP 400 with:

{
  "detail": "Human-readable error message"
}

See Also