DEV Community

FatherSon
FatherSon

Posted on

Building a Two-Layer AI Trading System for Polymarket & Kalshi: Brain + Hands Architecture That Runs While You Sleep

Most “AI trading agents” are just fancy chat wrappers that hallucinate commands and need constant babysitting. This system is different — a true two-layer architecture with a supervisory Brain and a deterministic local Hands executor. It paper-trades prediction markets unattended for days, hunts real mathematical arbitrage, and only escalates when truly stuck. Here’s the technical blueprint.

Polymarket Trading Bot

Why Single-Layer Agents Fail in Production

One model trying to plan, code, execute, recover from crashes, and manage risk leads to context overload and brittle behavior. The fix: strict separation of concerns via a shared workspace folder acting as a deterministic communication bus (task files, logs, state machines).

Brain Layer (Supervisory AI)

  • Uses Claude Desktop + Model Context Protocol (MCP) for safe local filesystem access.
  • Writes structured task specs (JSON/markdown) into the workspace.
  • Reads execution logs and results.
  • Decides retries, refinements, or human escalation.
  • Never touches APIs or executes trades directly — stays high-level and safe.

Key config tip: Restrict MCP filesystem server to only your ai-workspace directory. Explicit user approvals per sensitive action add a safety boundary.

Hands Layer (Execution AI)

  • Runs locally with Ollama (cheap/free models) + OpenClaw agent runtime.
  • Picks up tasks autonomously via heartbeat loop (checks HEARTBEAT.md every ~30 min by default).
  • Executes with strict tool constraints: filesystem in workspace only, whitelisted HTTP to exchange endpoints.
  • Writes deterministic logs, state, and results back to shared folder.
  • Supports crash recovery through explicit state files.

Pro tip: Use moderate context windows (8k–32k) + file retrieval instead of stuffing everything into every prompt for better throughput.

Trading Logic: Hard Constraints, Not Probabilistic Guessing

Focus on mathematical arbitrage only:

  • Complement constraint (binary markets): YES + NO must equal $1 at settlement.
  • Partition constraint (categorical): Exactly one outcome resolves true.

Pipeline:

  1. Normalized market adapters for Polymarket (CLOB, WebSocket) and Kalshi (demo + prod APIs).
  2. Detect price violations vs. logical identities, incorporating real fees, spreads, and depth.
  3. Compute risk-defined portfolios via simple LP or closed-form checks.
  4. Simulate fills conservatively (no orphan legs, slippage buffers).

Paper trade everything first with full replayability and P&L reconciliation before considering real capital.

Security & Reliability Guardrails (Non-Negotiable)

  • Isolated workspace + dedicated OS user.
  • Tool allow-list (no arbitrary shell or browsing).
  • Secrets injected via env vars, never written to workspace.
  • Kill switch file (STOP) that halts new orders.
  • Max exposure limits, stale data rejection, abnormal variance safe-mode.

Why This Actually Works Unattended

Clear separation + file-based protocol = crash resilience. Brain handles judgment cheaply (cloud model), Hands runs at near-zero marginal cost locally. The result: a system that discovers opportunities, executes paper trades, logs everything, and only pings you for real decisions.

This isn’t a weekend demo. It’s production-grade engineering with explicit failure modes addressed upfront: rate limits, security boundaries, deterministic replay, and strict mathematical edges.

If you want your AI to trade while you sleep, build the layers properly.


If you have more questions, please feel free to contact me at any time: https://t.me/FatherSon97

Polymarket #Kalshi #PredictionMarkets #AITrading #TradingBots #AI Agents #MultiAgentSystem #AlgorithmicTrading #QuantitativeTrading #DeFi #Web3 #MCP #Ollama #OpenClaw #FinTech #AutomatedTrading

Top comments (0)