PolyPolice is a low-latency Polymarket copytrading engine built for disciplined trade replication, tight execution control, and production-oriented exchange plumbing.
The system watches a small set of target traders, detects fresh Polymarket trade activity, evaluates whether copying is still valid under live market conditions, and submits controlled marketable orders through the official CLOB client. It is designed for fast reaction times without abandoning exchange correctness, operational safety, or state consistency.
Most public Polymarket copy bots optimize for one of two things:
- simple signal copying with weak execution discipline
- aggressive execution with poor state management and weak recovery behavior
PolyPolice is built around a different priority order:
- Correctness under real exchange conditions
- Reproducibility and operational resilience
- Low latency and efficient execution
- Simple, auditable architecture
The result is a bot that aims to be fast, but not naive.
At runtime, PolyPolice:
- resolves each tracked trader to the correct Polymarket
proxyWallet - polls the Polymarket Data API for new
TRADEactivity - paginates activity to reduce missed bursts from active traders
- deduplicates signals and persists recent dedupe state across restarts
- maintains a live quote cache over the Polymarket market WebSocket
- consumes the authenticated Polymarket user WebSocket for own order and trade lifecycle updates
- applies execution gating based on signal age, quote age, price drift, side restrictions, and exposure limits
- submits
FOKorFAKmarket orders using the official@polymarket/clob-client - tracks pending exposure with local reservations so concurrent signals do not overconsume capital or inventory
- reconciles local positions against Polymarket state and survives process restarts with persisted runtime watermarks
The architecture is intentionally modular:
src/index.tsMain orchestration loop, startup preflight, signal handling, quote warming, and lifecycle wiring.src/polymarket.tsPolymarket gateway layer for Data API, Gamma API, and official CLOB SDK integration.src/trader-monitor.tsTrader activity polling, pagination, deduplication, and watermark handling.src/orderbook.tsMarket WebSocket quote cache with heartbeat support and dynamic subscriptions.src/user-ws.tsAuthenticated user WebSocket client for trade and order lifecycle events.src/risk.tsCopy decision logic, including price-drift checks, quote staleness, and exposure gating.src/executor.tsOrder submission path, temporary retry handling, reservation rekeying, and post-order reconciliation.src/state.tsLocal portfolio state, reservations, and confirmed trade application.src/runtime-store.tsPersistent runtime state for dedupe keys and trader watermarks across restarts.
The operational flow is:
- Load configuration and initialize the Polymarket gateway.
- Derive or load API credentials for L2 authenticated CLOB access.
- Run a live-trading preflight:
- closed-only mode check
- collateral balance check
- collateral allowance check
- Resolve tracked trader addresses into Polymarket proxy wallets.
- Restore runtime watermarks and recent dedupe keys from persisted state.
- Start monitoring:
- Data API trader activity polling
- market WebSocket for quotes
- user WebSocket for own fills and order lifecycle
- For each candidate copy signal:
- fetch or reuse a fresh quote
- verify signal age and quote freshness
- verify price drift against the source trade
- verify side restrictions and sizing limits
- reserve inventory or exposure locally
- submit the order
- Maintain consistency:
- user WebSocket events update confirmed trade state
- periodic position refresh reconciles any drift
- runtime watermarks and dedupe state are persisted for restart safety
PolyPolice is not just another wallet watcher that blasts orders into the exchange.
What meaningfully differentiates it:
- It uses the Polymarket user WebSocket instead of relying purely on periodic position polling for own execution state.
- It keeps local pending reservations so concurrent signals do not accidentally double-spend exposure or inventory.
- It persists watermarks and dedupe state across restarts, which reduces replay and duplicate-copy risk after process recovery.
- It uses paginated activity catchup rather than a single shallow activity read.
- It reacts to Polymarket-specific exchange realities:
- market/user WebSocket heartbeats
- matching-engine restart
425behavior - tick-size change invalidation
- proxy wallet / funder distinctions
This is the difference between “it copies trades in happy-path demos” and “it is structured for sustained operation.”
This project is optimized for a narrow but realistic use case:
- low-latency copytrading
- 1 to 3 tracked traders
- marketable execution, not passive market making
- controlled position sizing
- exchange-constrained, not mempool-based latency assumptions
It is not intended to be:
- a generalized arbitrage engine
- a high-frequency maker bot
- a portfolio optimizer
- a backtesting platform
- an alpha discovery system
PolyPolice follows Polymarket’s documented architecture:
- trader detection comes from the Polymarket Data API activity feed
- live price context comes from the market WebSocket
- own lifecycle updates come from the authenticated user WebSocket
- order entry is done through the official TypeScript CLOB SDK
This matters because Polymarket does not expose a public wallet-specific target-trader stream that replaces activity polling for the use case we are solving.
Low latency matters, but fake speed is worse than disciplined speed.
The system prioritizes:
- connection reuse and keep-alive on hot HTTP paths
- live WebSocket quotes over unnecessary REST reads
- batch quote reads when REST fallback is required
- minimal main-loop drift
- concurrent execution with reservation-based protection
- event-driven reconciliation where Polymarket provides it
It explicitly avoids:
- blindly reusing stale quotes after exchange restarts
- optimistic local state changes without follow-up reconciliation
- over-trading due to missing pending-order awareness
- Node.js 22+
- a Polymarket-compatible funded wallet
- valid Polymarket account configuration
- trading allowed in your jurisdiction and for your account
npm installCopy the environment template:
cp .env.example .envMinimum required fields:
PRIVATE_KEYFUNDER_ADDRESSSIGNATURE_TYPETRADERS_JSON
Recommended production-adjacent fields:
USER_WS_ENABLED=trueCOPY_ON_STARTUP=falseSTATE_FILE_PATH=.runtime-state.json
Use conservative settings first:
DRY_RUN=true
POLL_INTERVAL_MS=250
MAX_USDC_PER_TRADE=10
MAX_USDC_GLOBAL=100
MAX_PRICE_DRIFT_BPS=15
MAX_QUOTE_AGE_MS=1500
DEFAULT_ORDER_TYPE=FOK
USER_WS_ENABLED=trueStart the bot:
npm run devMAX_USDC_PER_TRADEHard per-trade copy cap.MAX_USDC_GLOBALGross exposure ceiling for buy-side copy activity.CIRCUIT_BREAKER_MAX_FAILURESNumber of consecutive failed executions before the bot temporarily stops sending new orders.CIRCUIT_BREAKER_COOLDOWN_MSCooldown period while the circuit breaker remains open.METRICS_LOG_INTERVAL_MSInterval for structured runtime metrics snapshots.DEFAULT_ORDER_TYPEFOKfor all-or-nothing marketable execution,FAKfor partial immediate fills.MAX_SLIPPAGE_BPSPrice bump used when forming marketable orders.MAX_PRICE_DRIFT_BPSMaximum allowed drift between target trader fill price and your current executable price.MAX_QUOTE_AGE_MSQuote freshness threshold before rejecting or re-fetching execution context.
POLL_INTERVAL_MSTrader activity polling cadence.SIGNAL_TTL_MSMaximum acceptable age of a copied signal.COPY_ON_STARTUPWhether to copy immediately visible activity on the first poll after boot.
STATE_FILE_PATHLocal persisted runtime state file for dedupe keys and trader watermarks.POSITION_REFRESH_MSPeriodic reconciliation cadence against live Polymarket positions.
Each trader entry supports:
nameaddressmultipliermodeproportionalfixed_usdc
fixedUsdcbuyOnlysellOnly
Before live trading, PolyPolice performs:
- closed-only mode detection
- collateral balance check
- collateral allowance check
During operation, it uses:
- signal deduplication
- quote staleness checks
- price drift rejection
- reservation-based pending exposure protection
- user-WebSocket-driven state updates
- periodic reconciliation against exchange positions
- strong Polymarket-specific plumbing for a copytrading bot
- low-latency execution path without sacrificing exchange correctness
- explicit pending exposure handling
- restart resilience via persisted runtime state
- documented, auditable control flow
This system is advanced, but it is not magic.
Important platform and design limits remain:
- target-trader discovery still depends on the Data API, which is not a private ultra-low-latency feed
- same-block or near-same-block replication is possible in some liquid conditions, but never guaranteed
- the user WebSocket improves own-state handling, but there is still room for a fuller pending-/partial-fill state machine
- exchange restarts, quote staleness, and queueing behavior can still reduce realized copy quality
The next meaningful upgrades would be:
- full order-aware pending and partial-fill state machine
- structured metrics and SLOs for signal lag, order latency, and reconciliation drift
- circuit breakers based on reject streaks, drift, or WebSocket degradation
- replay and soak testing with recorded exchange event sequences
- stronger deployment ergonomics for long-running production use
Run type checking:
npm run checkRun tests:
npm testThis software is for accounts you control and only where use of Polymarket and automated trading is lawful for you.
You are responsible for:
- legal compliance
- key management
- exchange access
- capital risk
- production operations
PolyPolice is intended to be a serious Polymarket copytrading engine, not a marketing wrapper around a fragile script.
The repository emphasizes:
- exchange-aware engineering
- explicit control over execution risk
- readable, modular code
- realistic operational assumptions
- production-oriented behavior over demo simplicity