Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

PolyPolice

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.

Why This Exists

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:

  1. Correctness under real exchange conditions
  2. Reproducibility and operational resilience
  3. Low latency and efficient execution
  4. Simple, auditable architecture

The result is a bot that aims to be fast, but not naive.

What The System Does

At runtime, PolyPolice:

  • resolves each tracked trader to the correct Polymarket proxyWallet
  • polls the Polymarket Data API for new TRADE activity
  • 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 FOK or FAK market 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

Core Design

The architecture is intentionally modular:

  • src/index.ts Main orchestration loop, startup preflight, signal handling, quote warming, and lifecycle wiring.
  • src/polymarket.ts Polymarket gateway layer for Data API, Gamma API, and official CLOB SDK integration.
  • src/trader-monitor.ts Trader activity polling, pagination, deduplication, and watermark handling.
  • src/orderbook.ts Market WebSocket quote cache with heartbeat support and dynamic subscriptions.
  • src/user-ws.ts Authenticated user WebSocket client for trade and order lifecycle events.
  • src/risk.ts Copy decision logic, including price-drift checks, quote staleness, and exposure gating.
  • src/executor.ts Order submission path, temporary retry handling, reservation rekeying, and post-order reconciliation.
  • src/state.ts Local portfolio state, reservations, and confirmed trade application.
  • src/runtime-store.ts Persistent runtime state for dedupe keys and trader watermarks across restarts.

End-To-End Flow

The operational flow is:

  1. Load configuration and initialize the Polymarket gateway.
  2. Derive or load API credentials for L2 authenticated CLOB access.
  3. Run a live-trading preflight:
    • closed-only mode check
    • collateral balance check
    • collateral allowance check
  4. Resolve tracked trader addresses into Polymarket proxy wallets.
  5. Restore runtime watermarks and recent dedupe keys from persisted state.
  6. Start monitoring:
    • Data API trader activity polling
    • market WebSocket for quotes
    • user WebSocket for own fills and order lifecycle
  7. 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
  8. 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

Why This Pipeline Is Different

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 425 behavior
    • 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.”

Assumptions And Scope

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

Exchange Model

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.

Performance Philosophy

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

Setup

Requirements

  • Node.js 22+
  • a Polymarket-compatible funded wallet
  • valid Polymarket account configuration
  • trading allowed in your jurisdiction and for your account

Install

npm install

Configure

Copy the environment template:

cp .env.example .env

Minimum required fields:

  • PRIVATE_KEY
  • FUNDER_ADDRESS
  • SIGNATURE_TYPE
  • TRADERS_JSON

Recommended production-adjacent fields:

  • USER_WS_ENABLED=true
  • COPY_ON_STARTUP=false
  • STATE_FILE_PATH=.runtime-state.json

First Run

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=true

Start the bot:

npm run dev

Key Configuration

Execution Controls

  • MAX_USDC_PER_TRADE Hard per-trade copy cap.
  • MAX_USDC_GLOBAL Gross exposure ceiling for buy-side copy activity.
  • CIRCUIT_BREAKER_MAX_FAILURES Number of consecutive failed executions before the bot temporarily stops sending new orders.
  • CIRCUIT_BREAKER_COOLDOWN_MS Cooldown period while the circuit breaker remains open.
  • METRICS_LOG_INTERVAL_MS Interval for structured runtime metrics snapshots.
  • DEFAULT_ORDER_TYPE FOK for all-or-nothing marketable execution, FAK for partial immediate fills.
  • MAX_SLIPPAGE_BPS Price bump used when forming marketable orders.
  • MAX_PRICE_DRIFT_BPS Maximum allowed drift between target trader fill price and your current executable price.
  • MAX_QUOTE_AGE_MS Quote freshness threshold before rejecting or re-fetching execution context.

Signal Controls

  • POLL_INTERVAL_MS Trader activity polling cadence.
  • SIGNAL_TTL_MS Maximum acceptable age of a copied signal.
  • COPY_ON_STARTUP Whether to copy immediately visible activity on the first poll after boot.

Runtime State

  • STATE_FILE_PATH Local persisted runtime state file for dedupe keys and trader watermarks.
  • POSITION_REFRESH_MS Periodic reconciliation cadence against live Polymarket positions.

Trader Configuration

Each trader entry supports:

  • name
  • address
  • multiplier
  • mode
    • proportional
    • fixed_usdc
  • fixedUsdc
  • buyOnly
  • sellOnly

Operational Safety

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

Current Strengths

  • 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

Current Limits

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

What Would Further Improve It

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

Development

Run type checking:

npm run check

Run tests:

npm test

Legal And Compliance

This 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

Repository Positioning

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

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages