Polytraders Dev Guide
internal
v3 spine Phase 1 · Shared contracts 9 demo-wired · 0 shadow-ready · 0 production-live · 100 pending · 109 total 15/33 infra tasks the plan status board
internal · do not share externally

Polytraders: a controlled trading-infrastructure layer for prediction markets.

The software layer between a trading strategy and a live prediction-market exchange. It handles safety checks, order routing, audit trail, and reporting — so every strategy author builds on the same guardrails instead of reinventing them. This guide documents 109 frozen bot specifications and the standards every one of them must meet.

109frozen specs
9demo-wired
0shadow-ready
0runtime-live
0production-live
5classes

All specs documented. None in production. This guide is the build plan.

platform mock · start here · demo-wired ≠ production-live Open the platform mock — watch one trade flow through all 11 stages → Registry → book → canonical state → signals → fair value → execution → decision → OMS → inventory → replay → monitoring. 300+ pages · 9 demo-wired bots · the full operator UX.

The platform mock is the source of truth for what each stage exposes. The dev-guide pages below — stages, standards, pipelines — explain how to code what the mock shows.

What this is, in plain English

What is a prediction market?

A prediction market is a financial exchange where you buy and sell shares in the outcome of a future event — “Will X happen?” trades like a stock. If you think YES is underpriced at 30 cents, you buy; if it resolves YES, it pays $1.00. Polymarket is the largest on-chain prediction-market exchange. Polytraders is infrastructure for automated trading on Polymarket — not a product for users to gamble with, and not copy-trading.

What is Polytraders?

Polytraders is a layered software system that sits between a trading strategy and the Polymarket exchange. A strategy author writes the logic for when and why to trade. Polytraders handles everything else: scanning markets for quality, collecting signals, enforcing risk limits, signing and routing the order, recording the fill, and producing an audit trail. Nothing reaches the exchange unless every risk gate has cleared. The system targets Polymarket's CLOB V2 exchange and uses pUSD only.

Why build it in layers?

A single script that “does everything” is untestable, unauditable, and catastrophic when it fails. Layers separate concerns: a Discovery bot only finds markets; a Strategy bot only decides what to trade; a Risk guardrail only votes on whether to allow the trade. Each layer has a strict contract — it can only do what its class permits. If a Risk guardrail rejects an order, no downstream code can override it. Layers mean you can test, audit, and replace one component without touching the others.

Terms used on this page

CLOB V2
Central Limit Order Book, version 2. Polymarket's on-chain order matching engine. All Polytraders orders target CLOB V2 only — V1 is blocked.
EIP-712 v2
An Ethereum signing standard that encodes what you're signing in a structured, human-readable format. Every Polytraders order must be signed using the V2 domain separator. Wrong domain = hard reject.
pUSD
Polymarket's dollar-pegged stablecoin. The only currency used for orders in this system. Not USDC.e, not raw USDC — pUSD only.
builderCode
A tag attached to every Polytraders order that attributes fills to the Polytraders builder. Required for Polymarket's builder-rewards program and for the Governance layer's reconciliation checks.
CTFExchangeV2
The on-chain contract address for the Polymarket Conditional Token Framework exchange, V2. ContractAddressGuard enforces that every order targets this exact address.
OrderIntent
A structured internal object that Strategy emits when it wants to trade. It describes the market, direction (YES/NO), side (buy/sell), price, and size. Every Risk guardrail votes on an OrderIntent before it becomes a real order.
ReportEnvelope
The standard audit record that wraps every trade lifecycle event — from OrderIntent creation through fill confirmation. The Governance layer writes one per order. It is the primary artefact for reconciliation and compliance.
platform · 11 stages

The operating loop: how one trade goes from raw data to fill

Every trade passes through the same eleven stages. Each stage has a single responsibility and a reference TypeScript implementation in packages/polytraders-*. Open the 11-stage index →

Eleven stages grouped into Sense, Decide, Act, Verify SENSE · STAGES 1–4 DECIDE · STAGES 5–7 ACT · 8–9 VERIFY · 10–11 1RegistryMarketregistrytick · fees 2IngestBook &freshnessseq · stale 3StateCanonicalstateevent_id · hash 4SignalsSignalvectorimb · flow 5Fair valuep̂ + bandLB · UB · buffer 6Exec. est.q_execslippage · fees 7 · GATEDecision& risknet_edge · caps · kill 8OMSOrderson CLOB V2EIP-712 v2 9InventoryReserve &settlefree · reserved 10 · ReplayParitycheckBrier · hash 11 · SLOMonitor& rolloutcanary · kill Replay + monitoring feed back into registry, signals and risk on every cycle net_edge = p̂ − q_exec − fees − uncertainty_buffer One trade, eleven stages, four phases Click any stage to read how to code it. The gate at stage 7 is where every trade is approved or stopped.
Sense → decide → act → verify. The dashed line is the feedback path: replay + monitoring report back into registry, signals, and risk on every cycle so the system gets safer, not riskier, with scale.
How the backend fits together Operator surfaces sit on top of a deterministic runner. Each stage processor reads a typed contract, writes a typed contract, and reports to a single envelope. Bot families implement the stages. OPERATOR SURFACES · /mock-app/* Trader Homedaily ops + alerts Ops Dashboardhealth · kill switches Positionsexits + kill switches Marketsuniverse + workbench OrdersOMS · lifecycle Pipelinelive stage trace RUNTIME · packages/polytraders-runner pipeline.js · context.js · ReasonCode registry · ReportEnvelope writerDeterministic 11-stage loop. Each stage reads a typed contract, writes a typed contract, emits a reason code. One trade = one envelope. STAGE PROCESSORS · stages/* · 11 stages in 4 phases SENSE · stages 1–4Registry · Ingestion · StateSignals (read-only)writes MarketSnapshot DECIDE · stages 5–7Fair Value · Exec EstimateDecision + Risk (GATE)writes RiskVote, ExecutionPlan ACT · stages 8–9Orders + OMSInventory + Settlementwrites OrderIntent, Fill VERIFY · stages 10–11Replay + ValidationMonitoring + Rolloutwrites ReportEnvelope feedback SHARED CONTRACTS + 109 BOT SPECS · packages/polytraders-contracts · classes/* Typed contracts: MarketSnapshot · OrderIntent · RiskVote · ExecutionPlan · ReportEnvelope · FillEvery bot reads and writes these. No stage may invent its own shape. INTELread-only signals DISCdiscovery + filters STRATstrategies + sizing RISKguardrails + kills EXECrouting + OMS SECaccess + audit GOVpolicy + rollout 109 bots total, all frozen — runnable in mock, gated for production. EXTERNAL · production endpoints · V2 ONLY Polymarket CLOB V2 · EIP-712 v2builderCode 0xb000000000000000000000000000000000000000000000000000000000000000003f7a CTFExchangeV2on-chain settlement contract pUSD on Polygononly quote asset · no USDC.e Dev-only side packages (not in production path): polytraders-synthdata (synthetic books) · polytraders-mock-clob-v2 (in-process CLOB) · polytraders-backtest (replay engine). Backtests are not forecasts.
Top to bottom — what an operator sees, what runs it, what each stage does, what data shape they share, where it lands. The dashed feedback line is the same loop as the process diagram: verify writes back into sense on every cycle.
Shared operating rule: net_edge = p_hat − q_exec − fees − uncertainty_buffer. No stage may skip the one before it. That is what makes a trade explainable and safe enough to scale.
read this first

If you only build the rails, build them in this order.

These are the infrastructure modules you build before any trading strategy goes near real capital. If you skip Tier 1, you have no kill switch, no audit trail, and no safety net.

  1. Tier 1 — Mandatory rails (14 modules): clean data, ReportEnvelope, KillSwitch, ComplianceGate, PortfolioGuard, StaleBookGuard, MarketHaltDetector, SmartRouter, OrderLifecycleManager, PnL Reporter, ConfigDriftDetector, ReplaySimulator, plus the ReasonCode registry. Build these before anything else. See the Plan →
  2. Tier 2 — First trading path (4 modules): Maker-Tight + Cross-Market Arb + Fee/Slippage Estimator + Anti-Toxic Fill. The path that proves the rails work end-to-end.
  3. Tier 3 — Alpha expansion: news, sports, social, ontology, resolution. Only after Tier 1 is at runtime-live.

Current readiness, honestly

StateCountWhat it actually means
docs-complete109 / 109Every spec page is filled out across all 29 sections. Documentation completeness only — no implementation guarantee.
demo-wired9 / 109Reference implementation runs against the synthetic feed in the browser demo and ships a complete fixture pack. Not production-live. No capital, no live adapter.
shadow-ready0 / 109Has fixture pack, has passed CI on all four readiness scores, ready for shadow mode.
runtime-live0 / 109Has run in shadow with clean telemetry; promoted through the modes ladder.
production-live0 / 109Running against production constraints. Nothing here yet.

Synthetic backtests are not forecasts. Demo-wired ≠ production-live. See Definition of Done for the four readiness scores.

what's next

Open work, visible

  • Readiness taxonomy: replace the legacy live/beta/planned labels on spec pages with the five-state taxonomy above. Tracked as P0 #5.
  • Fixture packs: the 9 demo-wired bots need fixtures/<botId>/{normal,warning,hard,failure}.json. verify.js warns today; CI will fail once these land.
  • Spec/registry alignment: risk.marketqualityguard aliases disc/marketqualityranker; risk.drawdownguard aliases risk/portfolioguard. Aliases acceptable temporarily; dedicated spec pages owed.
  • Atomic exposure: risk.portfolioguard currently checks open positions; needs to atomically include pending orders + partial fills before any second strategy ships.
  • Production-engine notes: idempotency, retry policy, monotonic clock, cancel-before-place, event sourcing — the runner is a reference pipeline, not the production execution engine.
v3 spine

From spec library to running system.

v2 shipped 27/27 documentation for every bot — spec coverage, not running code. v3 separates documentation from implementation from runtime. The bot library is frozen at 109 frozen specifications — no new bots until the runtime rails (kill switch, reconciler, replay, envelopes) are at runtime-live with 24h of clean envelopes.

109 docs-complete 9 demo-wired 0 shadow-ready 0 runtime-live 0 production-live
v3.5 · backtest · synthetic browser demo · LLM optimizer

Nine bots wired into the synthetic replay stack.

These are reference implementations, not production-live. They run end-to-end against a deterministic synthetic feed with full order-book ladders, against the same TypeScript that compiles against @polytraders/contracts. They are demo-wired — they have not yet passed shadow-mode validation, fixture packs, or runtime promotion gates. Treat them as implementation references until the four readiness scores are complete. Click any chip to open its spec page; click Run in demo to watch it react in your browser. Synthetic backtests are not forecasts.

All 109 bots by layer — click any to open its spec.

Seven layers. Data flows in from the left (Discovery, Intelligence), decisions happen in the middle (Strategy, Risk, Security), and orders flow out the right (Execution). Governance sits across all of it. 109 docs-complete · 9 demo-wired · 0 production-live

DiscoveryFind markets
IntelligenceGather signals
StrategyDecide to trade
RiskGuardrail vote
SecuritySigning check
ExecutionPlace order
GovernanceAudit & report
market data & signals flow in → risk gates → signed orders flow out
← fills & ReportEnvelope records flow back through Governance
Discovery
Find and rank markets that are tradeable at all.
6 bots · 0 demo-wired · 0 production-live
Security
Signing-surface and key-handling guardrails. Run alongside Risk.
9 bots · 0 demo-wired · 0 production-live
demo-wired docs-complete reference bot click any bot → spec page

Pick a class. Then a bot.

Functional classes. Each class is a contract — what authority a bot in that class is allowed to hold and what it must never do.

Guardrail

Bots that can block, downsize, quarantine, or pause an order. They vote on every OrderIntent. A guardrail must have at least one REJECT path — if it cannot reject, it is not a guardrail and should be reclassified.

  • ComplianceGate · Risk demo-wired
  • KillSwitch · Risk demo-wired
  • MarketHaltDetector · Risk demo-wired
28 bots 6 demo-wired · 0 shadow-ready · 0 production-live 5 reference

Execution Utility

Bots that shape an approved order — price, timing, order type, size within constraints. They never change direction or strategy intent and never override a Risk decision.

  • SmartRouter · Execution demo-wired
  • AntiToxicFill · Execution
  • CancelReplaceOptimizer · Execution
13 bots 1 demo-wired · 0 shadow-ready · 0 production-live 1 reference

Alpha Strategy

The only bots in the stack that take directional, spread, or liquidity intent. Each declares its risk envelope to Layer 1 at startup; mid-run parameter changes require re-validation.

  • Maker-Tight · Strategy demo-wired
  • BasisTrader · Strategy
  • Breakout-Follower · Strategy
24 bots 1 demo-wired · 0 shadow-ready · 0 production-live

Signal Service

Read-only producers of typed signals. Every output carries a freshness timestamp and a provenance string. Signal services never submit orders.

  • MarketScanner · Discovery ref
  • AnomalyDetector · Intelligence
  • ContradictionDetector · Intelligence
21 bots 0 demo-wired · 0 shadow-ready · 0 production-live 1 reference

Governance Service

Bots that log, explain, reconcile, and audit. They sit across the top of everything else and produce the artefacts the team and users need to trust the system. Governance never blocks; it explains.

  • BuilderAttribution · Governance ref
  • AttributionRevenueReporter · Governance
  • Backtester · Governance
15 bots 0 demo-wired · 0 shadow-ready · 0 production-live 1 reference

Reference bots — fully specced

Eight bots authored end-to-end. Use these as the model when you author the next one.

0.1 Discovery LIVE
MarketScanner reference
MarketScanner continuously scans every live Polymarket market on each scan cycle and scores each one for tradability based on volume, book depth, spread, and resolution metadata. Markets that pass all filters emit an OrderIntent candidate to the Strategy layer for further evaluation. MarketScanner is strictly read-only — it never submits, signs, or modifies orders. All output is a recommendation that Strategy may accept or ignore.
Signal Service General live
1.2 Risk LIVE v3.5 · wired
KillSwitch reference
KillSwitch is the top-level emergency stop for the entire trading system. It can be triggered automatically when intraday or weekly drawdown exceeds a threshold, when the order-reject rate spikes above a circuit-breaker level, or when a market data feed is lost with open positions. It can also be triggered manually via the Admin UI. Once active, KillSwitch rejects every incoming OrderIntent without exception until a manual reset is performed (if require_manual_reset=true) or the trigger condition clears. It does not modify orders — it only blocks them entirely.
Guardrail General live
1.4 Risk LIVE
LiquidityGuard reference
LiquidityGuard prevents strategies from placing orders that would consume too much of the visible order-book depth on a given market. It checks book depth, spread, and top-of-book freshness on every OrderIntent and either approves, downsizes, or rejects the order. It cannot change the market, the direction, or the strategy intent — only the size and the timing of execution.
Guardrail General live
1.3 Risk LIVE
OracleRiskMonitor reference
OracleRiskMonitor watches the UMA Optimistic Oracle queue for proposals and active disputes on markets where open positions exist. When a market enters a resolution proposal or a dispute window, the bot can block new orders on that market, require reduced size, or flag a position for review. It protects against the scenario where a trade is submitted into a market moments before a contested resolution flips the outcome. It never overrides the strategy intent or changes the direction of an order — it only controls whether and how much the order is permitted to proceed.
Guardrail General live
1.1 Risk LIVE v3.5 · wired
PortfolioGuard reference
PortfolioGuard enforces account-wide exposure limits across every running strategy simultaneously. It tracks aggregate notional, rolling 24-hour drawdown, per-market concentration, and correlated-cluster concentration. When an incoming order would breach any of these limits, it is either downsized to the safe remaining budget or rejected outright. PortfolioGuard does not change the strategy intent, the market, or the direction — it only sets the maximum size an order is allowed to carry.
Guardrail General live
2.1 Execution LIVE v3.5 · wired
SmartRouter reference
SmartRouter translates an approved strategy intent into a concrete executable order by selecting the appropriate order type (FOK, GTC, or GTD), price, and timing. It may split a large order into iceberg child orders to reduce market impact. SmartRouter cannot change the direction of the trade, the target market, or the strategy intent — it is not permitted to flip the side (buy/sell), alter the outcome leg, or override any constraint set by the Risk guardrail pipeline. The only transformations it may make are to price, size scheduling, order type, and submission timing.
Execution Utility General live
5.8 Security PLANNED
ContractAddressGuard reference
ContractAddressGuard refuses to allow a signature or on-chain submission against any contract address that is not present on the committed CLOB V2 allow-list. It enforces the EIP-712 domain separator match against the expected V2 domain and rejects any order that targets a V1 Exchange address. This is a hard security control for the V1-to-V2 migration and must not be loosened without an explicit signed-off admin change. It cannot modify orders — it only approves or rejects.
Guardrail Ready to build
6.1 Governance LIVE
BuilderAttribution reference
BuilderAttribution tags every outgoing order with the Polytraders builder code before submission, logs each fill against the builder code, and reconciles the local fill log against the Polymarket builder-code report every 24 hours. If a discrepancy is detected — missing attribution, volume drift, or order counts that do not match — it quarantines the affected records and raises an alert. BuilderAttribution never submits, modifies, or cancels orders. Its authority is to explain and audit only.
Governance Service General live

Other ways to browse

How to read a bot page

  1. Top: identity table, pills, and one-line purpose. If you only have ten seconds, you stop here.
  2. Inputs: what Polymarket data and what internal data the bot needs. If a required input is missing in production, the bot must safe-fail.
  3. Parameters: machine name, default, warning, hard, plain meaning. The detailed block below explains why each default matters.
  4. Decision logic: when it APPROVES, RESHAPES, REJECTS, or only WARNS.
  5. Output: the standard RiskVote (or layer-equivalent) the bot returns.
  6. Failure modes + acceptance tests + Ready-to-ship checklist. If the checklist isn’t green, the bot doesn’t ship.