All projects

Case studyTrading system · AI research missions

Polymarket Twin Engine

Deterministic trading infrastructure for prediction markets, with Claude Code and Codex research missions running on top of it in sandboxes.

ivanmijatovic.com/projects/polymarket-twin-engineDiagram of the Polymarket Twin Engine: one shared core of market engine, strategy runner, order manager and portfolio, fed by either live WebSocket data or recorded Parquet replay, with live and simulated execution side by side.
Fig. 1Polymarket Twin Engine

Built as a unified execution engine where live trading and historical replay run through the exact same runtime, ensuring consistent strategy behavior and reproducible results.

I built it alone, from December 2025 to October 2026. What started as a trading bot with a backtest engine is now a platform: six recorded data feeds, a self-updating backtest fleet, and a runtime for long AI research missions.

  • Tick-level order book reconstruction
  • Shared execution pipeline (live & replay)
  • Deterministic portfolio & PnL accounting
  • Distributed backtest fleet with self-updating workers
  • Content-hashed strategy artifacts, shared by live and backtest

Sole architect and engineer · Automated trading system · Dec 2025 – Oct 2026

Deterministic execution · Backtesting engine · Live trading infrastructure · Event-driven architecture · Distributed backtest fleet · AI research runtime

01Overview

Project summary

A trading infrastructure platform built around one architectural constraint: live execution and backtesting must share a single execution path. No environment flags, no conditional branches - the same StrategyRunner, OrderManager, and Portfolio logic processes every event in both modes.

This constraint shaped every design decision. Market data is persisted as raw, ordered events in Parquet so replay can reconstruct exact book state. Strategies are schema-validated and plugin-driven so they remain portable across environments. Fills are latency-aware so backtest results reflect real execution dynamics. The result is a full research-to-production platform, not a trading bot with a backtest mode bolted on.

After January the same constraint carried the project much further. New execution features (post-only orders, per-market capital limits, synthetic feed ticks) were built into both modes at once. New data sources are verified by replaying them through the same order book code. And when strategy research moved out to its own repo, strategies came back as fixed, hashed bundles that run unchanged in backtests and live.

Project information
Trading system · AI research missions
Industry
Prediction Markets
Project type
Trading Infrastructure
Scope of work
Architecture, Backend Engineering, Trading Execution, Backtesting & Research Tooling, Data Platform, Distributed Systems, AI Research Infrastructure, Operations
Core technologies
TypeScript, Node.js, Python, Parquet, MySQL, WebSocket, Redis, BullMQ, DuckDB, Cloudflare R2, React, Next.js, Drizzle, Zod, Ethers, Ansible, Claude Code, Codex CLI

02At a glance

The project in brief

I built this alone: a Polymarket trading engine where live trading and backtests run the same code.

On top of it I built polymarket-protocols: Claude Code and Codex missions that run research for days in sandboxed workspaces. They can backtest on the shared fleet but cannot touch the engine, each other's folders or secrets. The missions made most of its 1,084 commits.

  • Impact

    1. One engine for backtests and live trading: any difference between them is treated as a bug
    2. Backtests run across a fleet of machines, at about 1.5 s per market measured over 73,000 market replays
    3. Live order placement averaged 116 ms and cancels 91 ms over 20 measured cycles
    4. Six live feeds recorded in one ordered sequence; each market is archived as one verified Parquet file
  • My Role

    1. Architected the execution pipeline and deterministic replay model
    2. Built ingestion + storage + replay engine (raw events → storage → reconstruction)
    3. Implemented order management, risk limits, and portfolio/PnL accounting
    4. Built the backtest fleet, data pipelines and AI research runtime, alone
  • Engineering Highlights

    1. Tick-by-tick replay with full market state reconstruction
    2. Unified execution engine for live trading and backtesting
    3. Parallel backtesting at scale: runs many independent simulations concurrently on shared datasets
    4. High-throughput data egress: streams and persists multi-GB/day market data
    5. Strategies shipped as sha256-identified artifacts: the same bytes run in backtests and live

03Case study

Problem

No backtesting infrastructure exists for Polymarket - strategies had to be tested live with real capital, with no way to validate behavior before deployment.

The gap isn't just tooling:

  • No existing solution: Polymarket has no backtesting system. Every strategy iteration required real money and real risk.
  • Unique market mechanics: binary outcomes, merge/redemption settlement, and time-bounded markets don't fit traditional trading tools.
  • No historical replay capability: without tick-level order book data and deterministic replay, strategy performance can't be measured or reproduced.
  • Unverifiable execution quality: simplified fill assumptions hide the spread, latency, and queue dynamics that determine real trading outcomes.

Building a backtesting engine for prediction markets meant solving all of these from scratch.

04Case study

Solution

Rather than adapting traditional backtesting tools, the architecture was designed specifically for prediction markets with one core constraint: live trading and historical replay must run through the same execution pipeline.

  • Unified execution engine: one StrategyRunner, one OrderManager, one Portfolio. The pipeline consumes events from either a live data source or a historical replay. Downstream logic doesn't know the difference.
  • Tick-level order book reconstruction: every raw CLOB event is recorded with strict ordering and timestamps, then replayed to reconstruct exact book state for realistic strategy evaluation.
  • Latency-aware fill model: execution simulates the real delay between order intent and exchange visibility, closing the gap between simulated and actual fill behavior.
  • Full prediction market settlement: portfolio accounting handles the complete market lifecycle including binary resolution, merge, and redemption, so PnL is fully resolved regardless of outcome.

The key insight was that execution determinism isn't a feature you add - it's an architectural constraint you design around from the start.

05Case study

After January: Scale and Trust

By January the engine worked end to end. The months that followed were about scale, and about being able to trust every result:

  • More data: recording Polymarket's feed alone was not enough. Recording added Binance and Chainlink prices, and history came from third-party archives that had to be checked before use.
  • More compute: replaying tens of thousands of markets one after another is slow. Backtests had to spread across several machines without giving them database access or trading keys.
  • Code identity: with research happening outside the engine repo, every machine had to prove it was running exactly the same strategy code.
  • Research time: long research runs needed to keep going for days, across machines, without a human watching every session.

Each answer kept the original rule: whatever runs live must also run, unchanged, in replay.

06Case study

System Architecture

The system is structured as a layered event-driven pipeline. Each layer has a single responsibility and communicates through a shared event model:

  • Ingestion layer: subscribes to Polymarket's CLOB WebSocket, persists every raw event with strict ordering, and handles window rotation and disconnect markers for dataset integrity. Since Recorder V4 it also captures Binance trades and quotes, Chainlink spot and TWAP prices and the website's price to beat, all in one shared receipt sequence.
  • Order book layer: reconstructs full book state tick-by-tick from the raw event stream. Operates identically on live and historical data.
  • Execution layer: the core event loop. Processes market ticks, invokes strategy evaluation, and routes orders through the OrderManager with full lifecycle tracking (intent queue, cancel/replace, status reconciliation).
  • Strategy layer: modular, schema-validated strategies registered with typed parameters. Supports an event-driven plugin system for computed signals and external data without coupling strategies to specific data sources.
  • Portfolio layer: tracks positions, open orders, fills, and realized PnL as a deterministic state machine. Environment-agnostic, including end-of-market settlement.
  • Storage layer: structured historical storage with per-window file rotation and explicit disconnect markers, so replays can distinguish between missing data and market silence. Today each market becomes one compact Parquet file in Cloudflare R2, checksum-verified after upload and listed in a MySQL catalog.
  • Distribution layer: a producer splits a backtest into one job per market on Redis/BullMQ; worker machines replay them on the same engine and an aggregator writes the results to MySQL.
  • Research layer: a runtime daemon on each machine runs AI research missions in sandboxed workspaces; their strategies reach the engine only as hashed artifacts.

The layers compose into the same pipeline in every mode. Swapping the data source is the only difference between live and replay.

07Case study

Engineering Highlights

  • Replay fidelity: tick-by-tick engine that reconstructs full order book state from raw WebSocket events, producing exact historical simulation down to individual book updates.
  • Extensible signal model: plugin architecture for attaching external data feeds (Binance klines, Deribit DVOL, custom indicators) as cached snapshots. Strategies consume signals through a uniform interface without knowledge of the data source.
  • Execution realism: latency-aware fill simulation that models intent-to-visibility delay, preventing the optimistic fill assumptions that inflate backtest performance.
  • Configuration safety: schema-validated strategy registration that enforces parameter types and constraints at load time, eliminating silent misconfiguration.
  • Systematic optimization: batch analytics and grid search tooling for evaluating strategies across parameter spaces, with feature export pipelines for offline analysis.
  • Two-clock price feeds: Binance and Chainlink data carry both their own time and the time they were received, so replay only shows a strategy what it could have known at that moment. Strategies can also wake on feed events, the same way live and in replay.
  • Execution features in both modes: post-only GTC/GTD orders, batch and scoped cancellation, shared event limits and per-market capital limits with reconciliation are implemented once and behave the same live and in backtests.
  • Verification gates: third-party history is replayed through the backtest order book and compared tick by tick with the raw data before use; every archive is read back and checksum-verified after upload.

08Case study

Data Platform

Backtests are only as good as their data. Since January the single recorder grew into a data platform with its own verification at every step:

  • Recorder V4: captures BTC 5- and 15-minute markets from six feeds, writes them to crash-safe journals, and turns each finished market into one compact Parquet file. It has no wallet or order code.
  • Verified archives: each file is uploaded to Cloudflare R2 only if it is not already there, read back and checksum-verified, then given a fixed manifest and listed in a MySQL catalog.
  • Smaller files, same results: on two sample markets the compact format is 80% and 83% smaller than the previous one, and replaying the 15-minute sample reproduced all 315,796 callbacks of the earlier verified run.
  • Historical pipelines: Telonex recordings (sync, download, convert, verify), the PMXT archive, Binance trades and Chainlink prices, with one data:sync command per machine role.
  • Market catalog: metadata for all 179,285 cataloged markets backfilled from Polymarket's Gamma API.
  • Offline research dataset: 122 days, 11,712 markets and 37.12 million trade rows in Parquet, queried locally with DuckDB.

09Case study

Backtesting at Scale

Backtesting moved from one laptop to a fleet of machines, managed from one place:

  • Job per market: BullMQ flows on Redis split a run into one job per market; worker machines replay them on the shared engine and an aggregator writes normalized results to MySQL.
  • No database or trading keys on workers: they need only Redis and read-only storage access.
  • Self-updating workers: every job carries the producer's commit; a worker that is behind pulls the new code and restarts once its current jobs finish. One fleet command puts every worker on new code in about 4–7 seconds.
  • Throughput: about 1.5 s per market across a 73,000-market replay profile, about 870 markets per minute on the fleet, and a full run over 10,747 markets with zero failures.
  • Fleet operations - Ansible playbooks and launchd services: status, data sync, update, start and stop in one command each, with unattended recovery after a reboot.
  • Dashboard and simulator: a Next.js dashboard for the fleet, backtest runs with profit and drawdown charts, datasets, recorders and costs, plus a simulator that plays back one market of a saved backtest tick by tick, with its recording verified.

10Case study

The Next Layer: polymarket-protocols

In July I added a Global Runtime to the engine: a daemon on each machine that runs long Claude Code or Codex missions as a series of fresh sessions. Missions keep their memory in files (MISSION, STATUS, JOURNAL, INBOX), and Mission Control, one dashboard page, starts, steers, pauses and stops them across the fleet.

In August I built polymarket-protocols, a separate repo of sandboxed research workspaces on top of it. I designed and built the system alone; the AI missions it runs made most of its 1,084 commits.

  • Sandbox per session: each session can write only to its own workspace; other workspaces are invisible, the engine is read-only, network is HTTPS through an allowlist, databases are reached only through local tunnels and secret files are blocked.
  • Hashed artifacts: research code reaches the engine only as one bundle identified by its sha256, checked by every backtest worker and by the live bot before it runs.
  • One owner per workspace: each workspace belongs to one machine, a pre-commit hook rejects changes to anyone else's, and sessions push straight to main, so git log is the activity feed of the whole fleet. A workspace moves only if the shared database shows no live run for it.
  • Two models, one task: the same research game is played side by side by a Claude and a Codex mission, with a dashboard to compare them and send guidance.
  • Engine knowledge: a shared, source-backed knowledge base about the engine (42 topics, 105 claims), with freshness checks that flag it for review when engine code changes.
  • Measurement at scale: a market-analytics tool reuses the engine's replay code; one run covered 10,000 markets and about 1.73 billion events.

The engine stays the one place where trading logic runs. The research layer only feeds it strategies it can verify.

11Case study

Metrics & Impact

  • Replay parity checked, not assumed: replaying the 15-minute validation market in the new recording format reproduced all 315,796 callbacks, order books, decisions and account events of the earlier verified run.
  • Order latency measured live: placement averaged 116 ms and cancel 91 ms over 20 cycles; Binance feed latency p50 110 ms, p95 254 ms, with zero mismatches against the exchange record.
  • Data at scale: 179,285 markets cataloged, six feeds recorded per market, and about 1.73 billion events measured across 10,000 markets in one research run.
  • Parallel backtesting: across multiple markets with parameter grid search for accelerated strategy evaluation - today on a fleet at about 870 markets per minute, with a 10,747-market run finishing with zero failures.
  • Live deployment: automated strategies executing in production with realized PnL tracking and full market settlement.
  • Engineering discipline: about 1,400 commits and more than 250 pull requests, CI on every pull request, 111 test files and a 154-page documentation site.
  • Experiment, not production: a Rust/NautilusTrader replay path ran about 5x faster than the TypeScript replay on 100-market sets, with matching decisions.

12Case study

Timeline

What was built, month by month (all of it by me):

  • December 2025 – January 2026: shared engine, Parquet recorder, plugins, latency-aware fills, parallel backtests, relayer and redeem, multi-bot live trading.
  • May 2026: documentation site and CI, Cloudflare R2, Telonex and PMXT pipelines, the BullMQ backtest fleet and the Next.js dashboard.
  • June 2026: self-updating workers, run extension, run detail and datasets pages, workers cost calculator.
  • July 2026: Binance and Chainlink feeds, synthetic feed ticks, one-command fleet operations and reboot recovery, Global Runtime and Mission Control.
  • August 2026: strategy artifacts, the runtime across several machines, and polymarket-protocols with its sandbox and ownership rules.
  • September 2026: post-only orders, per-market capital, the market simulator, Codex missions next to Claude.
  • October 2026: durable recorder, then Recorder V4 with its MySQL catalog, and the offline research dataset.

13Case study

My Role

Designed and built the entire platform end-to-end, alone:

  • Architecture: defined the single-pipeline constraint and layered event-driven design that ensures execution determinism across environments.
  • Data infrastructure: built the ingestion pipeline, storage layer, and replay engine with tick-level order book reconstruction.
  • Execution system: implemented the live trading engine including order management with risk limits, cancel/replace logic, and out-of-order fill handling.
  • Strategy platform: designed the modular framework, plugin system, and schema validation layer for portable, reproducible strategy development.
  • Research tooling: built batch analytics, grid search, and feature export pipelines for systematic strategy evaluation.
  • Operations: created CLI tooling for key management, balance checks, approvals, and multi-bot deployment workflows, and later fleet automation with Ansible, launchd and a menu-bar status plugin.
  • Distributed systems - built the backtest fleet: job flows, self-updating workers, the result aggregator and the dashboard.
  • Data platform: built Recorder V4, the verified R2 archive and catalog, and the historical data pipelines.
  • AI research infrastructure: built the Global Runtime, Mission Control and the polymarket-protocols sandbox.

14Design

Core Design Decisions

  • Backtesting System

    The backtesting engine replays recorded market data tick-by-tick, reconstructs the order book exactly as it appeared live, and runs the same StrategyRunner/OrderManager/Portfolio logic used in production. It supports latency simulation (intent -> exchange visibility) to better match real fills and includes market-end settlement logic (merge/redeem) so PnL is fully accounted for per market. This makes research outcomes far more realistic and reduces the typical live-vs-backtest gap.

  • Live Data Recording & Replay

    The system resolves the current markets, subscribes to the CLOB market WebSocket, and persists every raw event to Parquet with strict ordering and timestamps. Those files are rotated per window and include explicit disconnect markers, making the dataset auditable and safe to replay deterministically.

    Since October 2026 the recorder captures six feeds into one sequence and archives every market as a single verified Parquet file.

  • Strategy Framework

    Strategies are modular and registered with schema-validated parameters, so live runs and backtests are consistent and reproducible. The framework is event-driven (market ticks + account events), and it supports optional plugins to attach computed signals without changing core strategy code.

  • Strategy Plugins

    The execution engine includes a deterministic plugin layer that updates once per market tick and exposes cached snapshots to strategies. Plugins provide computed signals and external data while preserving identical runtime behavior across live and replay environments.

    • 100+ Technical Indicators: ATR, ADX, Bollinger Bands, realized volatility, and session metadata from external market data.
    • Rolling Volatility & Range Stats: window-based price movement and dispersion metrics per asset.
    • Time & Price Gates: configurable time-window trading controls and dwell constraints.
    • External Volatility Feeds: integrated sources such as Deribit DVOL aligned to market lifecycle.
    • External Data Requests: declarative external feed integration fulfilled at runtime.
  • Execution & Risk Management

    All orders flow through a central OrderManager that enforces risk limits and manages lifecycle (intent queue, cancel/replace, order status). Execution is abstracted so the same logic works in live trading and in backtests, with consistent handling of out-of-order fills.

    Post-only orders, scoped cancellation and per-market capital limits were later added once and work in both modes.

  • Portfolio & PnL Accounting

    A deterministic portfolio layer tracks positions, open orders, fills, and realized PnL. It is event-driven and consistent across live and backtest, including end-of-market settlement for complete PnL reporting.

  • Research & Optimization

    The project includes batch-level analytics, grid search tooling, and feature export pipelines so strategies can be tuned and evaluated at scale. This makes it a full research system, not just a trading bot.

  • Operations & Monitoring

    The system supports multi-bot deployments with per-bot configs and a lightweight monitoring UI. It also includes CLI tooling for key management, balance checks, approvals, and automation around Polymarket operational workflows.

    Today a Next.js dashboard covers the backtest fleet, datasets, recorders and AI missions.

  • Recorder V4

    Six feeds, one receipt sequence with wall and monotonic clocks, crash-safe journals per market, and one compact Parquet file when the market ends. Local files are deleted only after the R2 copy is read back and verified.

  • Backtest Fleet

    A producer resolves markets up front, so workers never touch the database or Polymarket's APIs. Jobs carry the producer's commit, workers update themselves, and the aggregator stores one normalized row per market.

  • Strategy Artifacts

    A strategy from another repo is bundled into one file identified by its sha256, stored in R2 and MySQL, and verified on every machine before it runs, live or in a backtest. The pte CLI runs engine commands from any folder.

  • Global Runtime

    Long AI missions run as a loop of fresh Claude Code or Codex sessions in sandboxed workspaces. Memory lives in files, not chat history, and one Mission Control page steers every loop on every machine.

15Diagrams

System diagrams

  • Sequence diagram of one order passing from strategy intent through the strategy runner, order manager and execution to the exchange, with fill and acknowledgement arriving in either order and the portfolio buffering an early fill until the order is known.
    Fig. 2One order, live or simulated: the fill can arrive before the exchange confirms the order, and the portfolio handles both orders of events.
  • Flow diagram: six live feeds merge into one receipt sequence, are written to a crash-safe journal, become one compact Parquet file per market when it ends, are uploaded to cloud storage, read back and checksum-verified, given a manifest, listed in a MySQL catalog and replayed on the same engine.
    Fig. 3Recorder V4: six feeds in one ordered sequence, one verified Parquet file per market, listed in a catalog for replay.
  • Bar chart: on a BTC 5-minute sample market the file shrank from 22.2 MB to 4.4 MB, 80.3 percent smaller; on a BTC 15-minute sample it shrank from 39.3 MB to 6.9 MB, 82.5 percent smaller.
    Fig. 4File size of the same captured events, previous recorder format vs Recorder V4, on two sample markets (from the project's validation notes; not an average).
  • Diagram of four data sources, the project's recorder, Telonex, Binance trades and Chainlink prices, each passing a verification check before landing in cloud storage, from which backtest worker machines sync their local data with one command.
    Fig. 5Each data source the backtests use passes a check before it is stored, then reaches every worker with one sync command.
  • Diagram: a producer splits a backtest into one job per market on a Redis queue; several worker machines without database credentials or trading keys replay the markets on the same engine using read-only data; an aggregator writes results to MySQL, which feeds the dashboard and simulator.
    Fig. 6One backtest, one job per market: workers replay on the shared engine with read-only data, and the aggregator stores the results.
  • Flow diagram: a job arrives with the producer's commit; if the worker's code matches it runs the job, otherwise it finishes its current jobs, pulls the new code, restarts and then runs. A side panel notes that one fleet command puts every worker on new code in about four to seven seconds, that launchd brings workers back after a reboot, and that the producer refuses uncommitted code.
    Fig. 7Every job carries the producer's commit; a worker that is behind finishes its current jobs, pulls the new code and restarts.
  • Flow diagram: strategy code in a research workspace is checked and published as one bundle identified by its sha256 hash, stored in cloud storage and MySQL, and downloaded by both backtest workers and the live bot, which verify the hash before running it.
    Fig. 8A strategy leaves the research repo as one hashed bundle; backtest workers and the live bot check the hash before running it.
  • Diagram: Mission Control steers a runtime daemon on each machine, which runs a mission as a loop of fresh Claude Code or Codex sessions that keep memory in mission, status, journal and inbox files; beside it, one session's sandbox: its own workspace is writable, other workspaces are invisible, the engine is read-only, network access is limited to allowed HTTPS, databases only through local tunnels, and secret files are blocked.
    Fig. 9Long AI missions run as a loop of fresh sessions with memory in files; each session can write only to its own workspace.
  • Stacked bar chart of commits per month from December 2025 to October 2026: the engine repo has 129 and 181 commits in December and January, almost none from February to April, 83 in May, 75 in June, a peak of 607 in July, 249 in August, 27 in September and 45 in October; the protocols repo adds 643 in August and 441 in September. Labels mark parallel backtests, the fleet and dashboard, new feeds and the runtime, strategy artifacts, the simulator and Recorder V4.
    Fig. 10Commits per month in both repos, December 2025 to October 2026; most commits in polymarket-protocols were made by the AI missions it runs.

16Contact

Book a free 20-minute call.

Tell me what your team does by hand every week. I’ll tell you whether an agent can take it over, and what it would need access to.