# Building an AI-Governed Trading Firm — Technical Architecture Guide

**Version**: 1.0  
**Last Updated**: 2026-04-21  
**Target Audience**: Engineers and system architects building autonomous trading desks  
**Scope**: Infrastructure, data flow, agent roles, risk controls, and operational mechanics. Trading strategy advice is kept marginal.

---

## Table of Contents

1. [Conceptual Overview](#1-conceptual-overview)
2. [System Architecture](#2-system-architecture)
3. [Agent Roles & Hierarchy](#3-agent-roles--hierarchy)
4. [Data Flow: From Market to Trade](#4-data-flow-from-market-to-trade)
5. [Communication Protocols](#5-communication-protocols)
6. [Paper Trading vs. Live Trading](#6-paper-trading-vs-live-trading)
7. [State Management](#7-state-management)
8. [Risk Management Infrastructure](#8-risk-management-infrastructure)
9. [Evolution Engine (Strategy Improvement)](#9-evolution-engine-strategy-improvement)
10. [Monitoring, Health Checks & Alerts](#10-monitoring-health-checks--alerts)
11. [Operational Playbook](#11-operational-playbook)
12. [Troubleshooting the Desk](#12-troubleshooting-the-desk)

---

## 1. Conceptual Overview

An AI-governed trading firm is a multi-agent system where specialized AI agents perform distinct operational roles under a hierarchical command structure. Unlike a single monolithic trading bot, this architecture separates concerns:

- **Governance** decides *whether* to trade and *how much* risk to take
- **Strategy** decides *what* to trade and *when*
- **Execution** handles *how* orders are placed and tracked
- **Infrastructure** keeps everything connected, logged, and recoverable

The human owner (the Board) sets high-level constraints. Everything below that level is autonomous.

---

## 2. System Architecture

### 2.1 Component Map

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                              BOARD (Human Owner)                            │
│  Sets: max drawdown, monthly budget, asset universe, exchange choice        │
└────────────────────────────────┬────────────────────────────────────────────┘
                                 │
┌────────────────────────────────▼─────────────────────────────────────────────┐
│                           PAPERCLIP ORCHESTRATOR                              │
│  Company: <Your_Company_Name>                                                │
│  ├── Task assignment & tracking                                               │
│  ├── Agent heartbeat monitoring                                               │
│  └── Dashboard & reporting                                                    │
└────────────────────────────────┬─────────────────────────────────────────────┘
                                 │
        ┌────────────────────────┼────────────────────────┐
        ▼                        ▼                        ▼
┌───────────────┐      ┌─────────────────┐      ┌─────────────────┐
│     CEO       │      │      CTO        │      │  Traders (1..N) │
│  (Governance) │◄────►│ (Technical Ops) │◄────►│  (Execution)    │
└───────┬───────┘      └─────────────────┘      └─────────────────┘
        │
        ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                         SINDBYTE MCP SERVER                                   │
│  Port: <MCP_PORT>            API Provider: <API_PROVIDER_PORT>               │
│  Tools: File I/O, Cloud APIs, TradingIQ, TradingAI, Math, System, Memory    │
└────────────────────────────────┬─────────────────────────────────────────────┘
                                 │
        ┌────────────────────────┼────────────────────────┐
        ▼                        ▼                        ▼
┌───────────────┐      ┌─────────────────┐      ┌─────────────────┐
│  LM-STUDIO    │      │  KRAKEN API     │      │  LOCAL FILES    │
│  (Reasoning)  │      │  (Execution)    │      │  (State/Logs)   │
│  Port: <LMS>  │      │  HTTPS          │      │                 │
└───────────────┘      └─────────────────┘      └─────────────────┘
```

### 2.2 Component Responsibilities

| Component | Responsibility | Failure Mode |
|-----------|---------------|--------------|
| **Paperclip** | Orchestrates agents, assigns tasks, tracks state | Desk becomes uncoordinated; agents run independently |
| **LM-Studio** | Provides LLM inference for agent reasoning | Agents cannot make decisions; desk halts |
| **SindByte MCP** | Tool execution layer — file, API, math, trading | Agents cannot act on decisions; desk paralyzed |
| **Kraken API** | Live market data and order execution | No prices, no fills; trades cannot execute |
| **Local Files** | Persistent state, logs, performance history | State loss on crash; no audit trail |

---

## 3. Agent Roles & Hierarchy

### 3.1 CEO (Chief Executive Officer)

**Technical Function**: Governance node with capital allocation authority.

**Capabilities**:
- Reads `performance.json` for all traders
- Reads market snapshots and daily briefing files
- Issues directives: HALT, RESUME, EVOLVE, REPLACE TRADER
- Allocates capital between strategies
- Sets daily loss limits and position sizing rules

**Adapter Config**:
```json
{
  "model": "lmstudio/<YOUR_MODEL>",
  "provider": { "lmstudio": { "options": { "baseURL": "http://127.0.0.1:<LMSTUDIO_PORT>/v1" } } },
  "mcp": { "sindbyte": { "type": "remote", "url": "http://127.0.0.1:<MCP_PORT>/mcp", "enabled": true } }
}
```

**Runtime**: `heartbeat.enabled: false`, `wakeOnDemand: true`, `maxConcurrentRuns: 1`

**Why wake-on-demand**: The CEO should only act when explicitly tasked (briefing review, board directive, or crisis). Continuous polling wastes tokens and can cause conflicting decisions.

### 3.2 CTO (Chief Technology Officer)

**Technical Function**: Evolution and infrastructure maintenance.

**Capabilities**:
- Runs `TradingIQ::Learning` to analyze strategy performance
- Triggers evolution cycles (mutate, backtest, graduate strategies)
- Monitors SindByte health
- Maintains a living bug log (e.g., `FOUND_PROBLEM.md`)
- Verifies data freshness before trading windows

**Key Workflow**:
1. Pull `performance.json` from all traders
2. Identify underperformers (< 50% win rate or negative Sharpe)
3. Trigger `TradingAI::DecisionMenu` → scan for strategy setups
4. Run paper trades on evolved variants
5. Graduate winners to live trading

### 3.3 Traders (Strategy Execution Agents)

**Technical Function**: Entry/exit signal generation and order placement.

**Typical Configuration**:
- **Trader-01**: Momentum / Trend-Following
- **Trader-02**: Mean-Reversion / Range
- **Trader-03** (optional): Breakout / Volatility

**Operational Cycle**:
1. Receive task: "Run momentum scan"
2. Fetch fresh market data via `CloudTools::KrakenRequest`
3. Run `TradingIQ::Scanner` or manual indicator check
4. Calculate position size (risk per trade = 2-5% of allocated capital)
5. If signal exists:
   - Paper mode: Log intended trade to `paper_state.json`
   - Live mode: Call `CloudTools::KrakenRequest` → `AddOrder`
6. Update `performance.json` with result

**Risk Parameters per Trader**:
```json
{
  "max_position_size_pct": 0.30,
  "max_daily_loss_pct": 0.05,
  "stop_loss_pct": 0.05,
  "take_profit_pct": 0.08,
  "asset_universe": ["XLM", "ADA", "DOGE", "VET", "FLOW"]
}
```

---

## 4. Data Flow: From Market to Trade

### 4.1 Price Discovery Pipeline

```
Kraken API (public)
    │
    ▼
SindByte CloudTools::KrakenRequest(endpoint="Ticker", params="pair=XLMEUR")
    │
    ▼
Agent receives JSON price data
    │
    ▼
Agent runs MathTools::ResolveFormula for position sizing
    │
    ▼
Agent writes decision to paper_state.json (paper) or calls AddOrder (live)
    │
    ▼
FileTools::AppendToFile logs trade to daily log
```

### 4.2 Order Execution Flow (Live)

```
Trader decides to buy 100 XLM @ market
    │
    ▼
Direct tool call: CloudTools::KrakenRequest
    │
    ├── endpoint: "AddOrder"
    ├── params: "pair=XLMEUR&type=buy&ordertype=market&volume=100"
    │
    ▼
SindByte builds Kraken private request:
    ├── Nonce (microsecond timestamp)
    ├── POST body signed with HMAC-SHA512 of API secret
    └── POST to https://api.kraken.com/0/private/AddOrder
    │
    ▼
Kraken responds with order ID
    │
    ▼
Trader logs: entry price, fill time, order ID, stop/target levels
    │
    ▼
Trader places stop-loss: AddOrder with ordertype=stop-loss
```

> **Critical**: The `ordertype` parameter must be passed directly to `CloudTools::KrakenRequest`. Routing through `ToolCatalog.CallTool` mangles this parameter and causes `EGeneral:Invalid arguments:ordertype`.

### 4.3 Data Freshness Requirements

Stale prices cause bad decisions. The pipeline enforces:

| Check | Threshold | Action if Failed |
|-------|-----------|------------------|
| Price snapshot age | < 15 minutes | Reject decision, fetch fresh |
| Kraken API latency | < 5 seconds | Retry once, then abort |
| Balance sync | < 30 minutes | Do not place orders |

---

## 5. Communication Protocols

### 5.1 Primary: Paperclip API

When Paperclip is healthy, all communication flows through it:

- **Tasks**: Assign work to agents
- **Dashboard**: View agent status, task counts
- **Activity**: View recent agent actions

Agents poll or are pushed tasks based on their `heartbeat` config.

### 5.2 Fallback: File-Based Communication

When Paperclip is down, the desk switches to a file-based message bus. This is the **operational fallback** and must be designed from day one.

**File Structure**:
```
<Project_Root>/
├── CEO_DAILY_BRIEFING_YYYY-MM-DD.md    # Daily status, positions, infrastructure health
├── TODAY.md                             # Current priorities and action items
├── FOUND_PROBLEM.md                     # Living bug log
├── Rules/
│   └── file-based-communication.md      # Protocol specification
├── PaperStates/
│   ├── paper_state_t1.json              # Trader-01 state
│   ├── paper_state_t2.json              # Trader-02 state
│   └── Trader-01.json, Trader-02.json   # Per-trader snapshots
├── Traders/
│   ├── trader-01/
│   │   ├── performance.json             # Win rate, P&L, Sharpe
│   │   └── TODAY.md                     # Trader-specific directives
│   └── trader-02/
│       ├── performance.json
│       └── TODAY.md
└── Logs/
    ├── market_snapshot_YYYY-MM-DD.json
    └── cheap_assets_snapshot.json
```

**Protocol Rules**:
1. Every agent writes its state to its designated file after each action
2. The CEO writes `CEO_DAILY_BRIEFING_*.md` once per day or after major events
3. Agents read `TODAY.md` and their own `TODAY.md` on wake
4. No file locking assumed — write atomically (temp file + rename)
5. Timestamp every entry so stale data can be detected

### 5.3 Agent Wake Sequence

When an agent starts (or wakes from idle):

1. Read `AGENTS.md` in its instructions directory (role definition)
2. Read `TODAY.md` and `CEO_DAILY_BRIEFING_*.md` (context)
3. Read its own `performance.json` and `paper_state_*.json` (state)
4. Connect to SindByte MCP and list available tools
5. Connect to LM-Studio and verify model responsiveness
6. Report readiness to Paperclip (or write to state file)

---

## 6. Paper Trading vs. Live Trading

### 6.1 Configuration Switch

The gate between paper and live is a single boolean in `mcp_config.json`:

```json
{
  "CloudToolsKrakenTradingEnabled": false
}
```

- `false` → All private trading endpoints (`AddOrder`, `CancelOrder`, `EditOrder`) return `TRADING_DISABLED`
- `true` → Real orders are sent to Kraken

**Operational Rule**: New strategies must run in paper mode for at least 50 trades or 2 weeks before graduation to live.

### 6.2 Paper Trade Simulation

Paper trades are **not** executed on an exchange. They are recorded locally:

```json
{
  "trade_id": "T1-001",
  "pair": "DOGE/USD",
  "side": "buy",
  "volume": 121.0,
  "entry_price": 0.09589,
  "current_price": 0.095014,
  "unrealized_pnl_pct": -0.91,
  "status": "open",
  "paper": true,
  "opened_at": "2026-04-20T22:00:00Z"
}
```

Current prices are fetched from Kraken public API to mark paper positions to market.

### 6.3 Graduation Criteria

A strategy graduates from paper to live when:
- Win rate ≥ 55%
- Profit factor ≥ 1.3
- Max drawdown ≤ 10%
- At least 20 closed trades
- CEO approves capital allocation

---

## 7. State Management

### 7.1 Single Source of Truth per Domain

| Domain | Source File | Owner |
|--------|-------------|-------|
| Account balance | Kraken API (`Balance` endpoint) | SindByte |
| Live positions | Kraken API (`OpenOrders`, `OpenPositions`) | Kraken |
| Paper positions | `PaperStates/paper_state_tN.json` | Trader-N |
| Performance metrics | `Traders/trader-0N/performance.json` | Trader-N |
| Daily plan | `TODAY.md` | CEO / Board Manager |
| Bug log | `FOUND_PROBLEM.md` | CTO |
| Market data | `Logs/market_snapshot_*.json` | CTO / Automation |

### 7.2 State Update Rules

1. **Live trades**: Kraken is the source of truth. SindByte fetches on demand.
2. **Paper trades**: Local JSON files are the source of truth. Sync every 15 minutes.
3. **Performance**: Recalculated after every closed trade. Written immediately.
4. **Briefings**: Generated once daily or after significant P&L moves (> 2%).

### 7.3 Backup Strategy

Paperclip auto-backs up its SQLite database daily.

SindByte state files should be backed up via:
- Git commits (if repository-backed)
- Periodic ZIP archives
- File sync to cloud storage

---

## 8. Risk Management Infrastructure

### 8.1 Hard Limits (Enforced by Configuration)

| Limit | Value | Enforcement |
|-------|-------|-------------|
| Max equity per trade | 30% of allocated capital | Trader config |
| Max daily loss | 5% of total equity | CEO directive + trader check |
| Max open positions | 3 live + 2 paper | CEO task assignment |
| Stop-loss mandatory | Yes, on every live trade | Pre-trade checklist |
| Exchange | Kraken only | `mcp_config.json` endpoint whitelist |

### 8.2 Circuit Breakers

The desk implements manual circuit breakers:

1. **HALT protocol**: CEO sets `status: halted` in `TODAY.md`. All traders stop scanning.
2. **Auto-halt triggers**:
   - SindByte crashes 3 times in 1 hour
   - Kraken API returns errors for > 10 minutes
   - Any live trade hits -5% without a stop-loss in place
   - Paperclip is down for > 30 minutes

### 8.3 Stop-Loss Execution

Kraken stop-loss orders are native exchange orders, not monitored by agents:

```
AddOrder:
  pair=XLMEUR
  type=sell
  ordertype=stop-loss
  price=0.1446
  volume=100
```

This ensures the stop executes even if all local infrastructure is down.

### 8.4 Take-Profit Strategy

Take-profit orders are **not** placed as native exchange orders (Kraken restricts parallel orders on the same position). Instead:
- Agents monitor price manually
- When target approaches (e.g., 80% of target), agent places a limit sell
- This avoids position reservation conflicts

---

## 9. Evolution Engine (Strategy Improvement)

### 9.1 Concept

Strategies are not static. They evolve through a Darwinian process:

1. **Selection**: Identify top-performing strategies by Sharpe ratio
2. **Mutation**: Randomly vary parameters (lookback periods, thresholds, position sizing)
3. **Backtest**: Run mutated variants on recent historical data
4. **Competition**: Paper-trade top 3 variants against the incumbent
5. **Graduation**: Replace incumbent if a variant outperforms over 20+ trades

### 9.2 Technical Implementation

The evolution cycle is driven by the CTO agent using these tools:

| Tool | Purpose |
|------|---------|
| `TradingIQ::Learning` | `action=stats` — reads historical performance |
| `TradingAI::DecisionMenu` | Scan for strategy setups |
| `MathTools::Optimizer` | Finds optimal parameter combinations |
| `MathTools::MonteCarlo` | Simulates strategy under random market conditions |
| `FileTools::Read/Write` | Stores variant definitions and backtest results |

### 9.3 Variant Storage

Each strategy variant is stored as a JSON file:

```json
{
  "variant_id": "MOM_v3_20260421",
  "parent": "MOM_v2",
  "mutation": {
    "lookback_hours": 24,
    "momentum_threshold_pct": 2.5,
    "volume_filter_min": 5000000
  },
  "backtest": {
    "period": "2026-03-01 to 2026-04-20",
    "trades": 47,
    "win_rate": 0.59,
    "profit_factor": 1.42
  },
  "status": "paper",
  "paper_trades": 0
}
```

---

## 10. Monitoring, Health Checks & Alerts

### 10.1 Automated Health Checks

A scheduled task or watchdog script should run every hour:

```powershell
# Conceptual health check script
$tests = @(
    @{ Name="SindByte MCP"; Uri="http://127.0.0.1:<MCP_PORT>/mcp"; Body='{"jsonrpc":"2.0","id":1,"method":"tools/list"}' },
    @{ Name="Paperclip"; Uri="http://127.0.0.1:<PAPERCLIP_PORT>/api/agents/me"; Headers=@{Authorization="Bearer <TOKEN>"} },
    @{ Name="LM-Studio"; Uri="http://127.0.0.1:<LMSTUDIO_PORT>/v1/models" },
    @{ Name="Kraken"; Uri="https://api.kraken.com/0/public/Time" }
)

foreach ($test in $tests) {
    try {
        Invoke-RestMethod -Uri $test.Uri -Method POST -Body $test.Body -TimeoutSec 10 | Out-Null
        "$($test.Name): OK"
    } catch {
        "$($test.Name): FAIL — $($_.Exception.Message)"
        # Alert: write to log, send email, or trigger recovery
    }
}
```

### 10.2 Key Metrics to Track

| Metric | Source | Alert Threshold |
|--------|--------|-----------------|
| SindByte uptime | Process monitor | Restart if down > 2 min |
| Agent heartbeat age | Paperclip API | Alert if > 10 min old |
| Task backlog | Paperclip dashboard | Alert if blocked > 20 |
| Equity drawdown | `performance.json` | HALT if > 5% daily |
| API latency | Kraken `Time` endpoint | Alert if > 5 seconds |
| Model load status | LM-Studio `/v1/models` | Alert if no model loaded |

### 10.3 Log Aggregation

Important logs to monitor:

| Log File | Location | Purpose |
|----------|----------|---------|
| Paperclip server log | Paperclip instance logs directory | API requests, errors |
| Paperclip stdout | Paperclip base directory | Heartbeat runs |
| Paperclip stderr | Paperclip base directory | Crash output |
| SindByte reliability | SindByte logs directory | Crash tracking |
| Windows Event Log | `Application` source | Process crashes |

---

## 11. Operational Playbook

### 11.1 Daily Startup Sequence

1. Start LM-Studio → Load model → Enable local server
2. Start SindByte executable
3. Start Paperclip (`paperclip run`)
4. Verify all agents show "active" in dashboard
5. Run health check script
6. CEO generates `CEO_DAILY_BRIEFING_*.md`
7. Assign scanning tasks to traders

### 11.2 Shutdown Sequence

1. HALT all traders (set `status: halted` in `TODAY.md`)
2. Wait for open orders to settle (or verify stop-losses are in place)
3. Stop Paperclip (agents will finish current tasks)
4. Stop SindByte
5. Stop LM-Studio (optional — can stay running)

### 11.3 Adding a New Trader

1. Create agent in Paperclip UI with role `general`
2. Set adapter config (same as other traders)
3. Create folder: `Traders/trader-03/`
4. Create `performance.json` with initial zeros
5. Define strategy parameters in a JSON file
6. Add to `tool_registration_categories` if new tool categories needed
7. Run 20 paper trades before live consideration

### 11.4 Recovering from Crashes

| Failed Component | Recovery Steps |
|------------------|----------------|
| SindByte crash | Restart executable. Check bug log for pattern. |
| Paperclip crash | Restart `paperclip run`. Check SQLite integrity. |
| LM-Studio crash | Restart LM-Studio, reload model. |
| Kraken API down | Switch to file-based comms. Monitor exchange status page. |
| Agent stuck | Kill agent process, reassign task in Paperclip. |

---

## 12. Troubleshooting the Desk

### 12.1 Common Failure Patterns

| Pattern | Likely Cause | Diagnostic |
|---------|-------------|------------|
| All agents idle, no tasks running | Paperclip down or tasks unassigned | Check dashboard |
| Agent runs but produces no trades | LM-Studio returning empty content | Check `max_tokens` ≥ 4096; model may need reload |
| Agent places orders but they fail | `CloudToolsKrakenTradingEnabled: false` | Check `mcp_config.json` |
| Stop-loss not triggered | Native order not placed correctly | Verify stop-loss in Kraken open orders |
| Stale prices in decisions | Snapshot not refreshed | Enforce < 15 min freshness rule |
| Tool returns garbage | Indicator tool may use simulated data | Verify against manual calculation from raw OHLC |

### 12.2 Debugging Agent Behavior

1. Read the agent's transcript in Paperclip UI
2. Check the agent's `TODAY.md` for its last action
3. Query SindByte directly with the same tool call the agent used
4. Compare LM-Studio response with expected output
5. If ToolCatalog wrapper suspected, switch to direct tool name

### 12.3 Escalation Path

```
Trader issue          → Trader checks logs, retries
Trader can't fix      → Escalate to CTO (technical bug)
CTO can't fix         → Log in FOUND_PROBLEM.md, assign severity
Critical (desk halt)  → Escalate to CEO / Acting Board Manager
CEO/Board decides     → HALT, EVOLVE, or manual intervention
```

---

## Marginal Trading Notes (For Completeness)

This document is intentionally architecture-focused. Strategy-specific guidance is minimal by design:

- **Momentum strategies** work best in trending markets with above-average volume
- **Mean-reversion** requires range-bound conditions and oversold indicators
- **Position sizing** should never exceed risk limits regardless of signal strength
- **Diversification** across uncorrelated assets reduces portfolio variance
- **Transaction costs** (fees, spread) must be factored into all calculations

For strategy development, refer to the `TradingIQ::Learning` tool outputs and the evolution engine workflow described in Section 9.

---

## Related Documents

| Document | Purpose |
|----------|---------|
| `SindByte-Paperclip-Setup-Guide.md` | SindByte + Paperclip technical setup |
| `Paperclip-Agent-Config.txt` | Agent adapter JSON snippets |
| `setup-mcp.ps1` | Automated .mcp.json deployment |
| `README.txt` | Quick-start summary |

---

*Document maintained by SindByte Distribution Team*
