Skip to content

ApolloPolyX/Polymarket-Arbitrage-Bot-V2

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Polymarket Arbitrage Bot V2

Production-focused Rust trading system for Polymarket 5m/15m workflows. This repository is organized for long-term maintainability: clean module boundaries, multiple runtime entrypoints, and operational binaries for trading lifecycle tasks.

Demo

Watch the bot in action:

polymarket-arb-bot-v2.mp4

Table of Contents


What This Project Is

Polymarket Arbitrage Bot V2 is a modular execution framework for event-driven market trading on Polymarket CLOB infrastructure. It is a multi-binary system with:

  • strategy runtime executables (src/bin/live)
  • research executables (src/bin/research)
  • operational executables (src/bin/tools)
  • reusable engine components (src/core, src/engine, src/strategy, src/connectors, src/analytics) This structure allows strategy evolution without destabilizing execution infrastructure.

Key Capabilities

  • Pre-order and dual-limit style workflows for short-duration markets.
  • 5-minute BTC-specific runtime variant.
  • Trailing strategy runtime variant.
  • Simulation mode for dry-run validation.
  • Backtest mode for historical replay and analysis.
  • Utility binaries for allowance, redeem, merge, and sell workflows.
  • Layered architecture to isolate strategy, execution, and transport.
  • Support for operator-first workflows with deterministic tools.

Architecture

The codebase follows layered architecture to separate concerns, reduce coupling, and improve operational debuggability.

Layer 1: Core (src/core)

Purpose: foundational contracts shared by all higher layers.

  • config.rs defines runtime configuration schema and loading behavior.
  • models.rs defines shared typed market/order/trade entities.
  • clob_sdk.rs defines low-level SDK integration boundary. Engineering intent:
  • keep this layer stable and generic,
  • avoid strategy-specific branching,
  • keep interfaces explicit and typed.

Layer 2: Connectors (src/connectors)

Purpose: all external integrations and protocol adaptation.

  • api.rs handles Polymarket API integration patterns.
  • rtds.rs handles real-time feed adaptation. Engineering intent:
  • isolate transport concerns,
  • normalize external payloads,
  • prevent connector details from leaking into strategy logic.

Layer 3: Engine (src/engine)

Purpose: orchestrate runtime loops and side-effectful execution.

  • monitor.rs drives market monitoring and time-window checks.
  • trader.rs executes order lifecycle actions and transitions. Engineering intent:
  • engine owns sequencing and state transitions,
  • strategy emits intent and policy,
  • trading side effects remain centralized.

Layer 4: Strategy (src/strategy)

Purpose: evaluate opportunities and produce decision outcomes.

  • detector.rs contains entry/trigger decision logic.
  • merge.rs contains merge and strategy-specific position logic. Engineering intent:
  • strategy modules should be testable in isolation,
  • strategy code should avoid direct network calls,
  • policy should be configurable rather than hard-coded.

Layer 5: Analytics (src/analytics)

Purpose: simulation and replay/backtest workflows.

  • simulation.rs contains simulation behavior and metrics semantics.
  • backtest.rs contains historical replay logic. Engineering intent:
  • reuse models/policies from runtime paths where feasible,
  • keep research code from contaminating live execution branches.

Layer 6: Entrypoints (src/bin)

Purpose: executable-level composition and mode-specific startup.

  • live/ contains strategy runtime binaries.
  • research/ contains backtest binaries.
  • tools/ contains operational utility binaries. Engineering intent:
  • keep binaries thin,
  • compose modules, do not duplicate domain logic,
  • preserve single responsibility per executable.

Runtime Architecture at a Glance

  1. Config and CLI flags initialize runtime contracts.
  2. Connectors create external communication channels.
  3. Monitor loop captures current market state.
  4. Strategy evaluates state and emits action intents.
  5. Trader converts intents into controlled order actions.
  6. Logs/artifacts are stored for audit and replay.

Why This Architecture Scales

  • Faster onboarding: clear separation by ownership boundaries.
  • Faster debugging: incidents map naturally to one layer.
  • Safer releases: strategy changes can ship without connector rewrites.
  • Better operations: tool binaries isolate high-risk manual tasks.

Execution Flows

Live / Simulation Flow

  1. Parse CLI arguments and load config.
  2. Initialize API and streaming connectors.
  3. Start market monitor loop.
  4. Build normalized snapshots.
  5. Evaluate strategy detector logic.
  6. Submit/cancel/hedge through trader engine.
  7. Record logs and outcome artifacts.

Tooling Flow

Operational binaries run single-purpose tasks:

  • allowance checks/approval,
  • explicit order tests,
  • redeem/merge operations,
  • targeted diagnostics. This is safer than editing production strategy binaries for ad-hoc tasks.

Research Flow

  1. Read history inputs from history/.
  2. Replay strategy behavior in controlled mode.
  3. Compare outcomes to live assumptions.
  4. Promote parameter changes only with replay evidence.

Repository Layout

Polymarket-Trading-Bot-Rust-V2/
├── src/
│   ├── core/
│   │   ├── config.rs
│   │   ├── models.rs
│   │   └── clob_sdk.rs
│   ├── connectors/
│   │   ├── api.rs
│   │   └── rtds.rs
│   ├── engine/
│   │   ├── monitor.rs
│   │   └── trader.rs
│   ├── strategy/
│   │   ├── detector.rs
│   │   └── merge.rs
│   ├── analytics/
│   │   ├── backtest.rs
│   │   └── simulation.rs
│   └── bin/
│       ├── live/
│       ├── research/
│       └── tools/
├── config.example.json
├── config.json
└── history/

Prerequisites

  • Stable Rust toolchain.
  • Valid Polymarket API credentials.
  • Trading wallet credentials and sufficient network balances.
  • Correct permissions for all wallet actions used in your flow.

Quick Start

1) Configure

cp config.example.json config.json

Edit config.json with credentials and strategy parameters.

2) Build

cargo build --release

3) Run in simulation first

cargo run -- --simulation

4) Run live

cargo run -- --no-simulation

Configuration

config.json is the operational contract for runtime behavior. Minimum validation checklist:

  • API key fields and endpoints.
  • wallet identity and signing config.
  • strategy thresholds and position size controls.
  • interval and timing settings. Recommended operator practices:
  • keep separate configs for dev, paper, and prod,
  • require review for parameter changes,
  • avoid promoting experimental thresholds without replay evidence.

Run Modes and Binaries

Default dual-limit executable

cargo run -- --simulation
cargo run -- --no-simulation

BTC 5m executable

cargo run --bin main_dual_limit_045_5m_btc -- --simulation

Trailing executable

cargo run --bin main_trailing -- --simulation

Backtest executable

cargo run --bin backtest -- --backtest

Tools and Operational Binaries

Binaries in src/bin/tools/:

  • test_allowance
  • test_cash_balance
  • test_limit_order
  • test_merge
  • test_multiple_orders
  • test_predict_fun
  • test_redeem
  • test_sell Example:
cargo run --bin test_allowance -- --approve-only

Use tools for explicit operational tasks rather than patching strategy binaries.

Backtesting Workflow

  1. Prepare artifacts under history/.
  2. Run backtest binary:
cargo run --bin backtest -- --backtest
  1. Compare outcomes against current live assumptions.
  2. Promote parameter changes only after deterministic review.

Deployment Guidance

For PM2/systemd style process managers:

  • run with explicit working directory,
  • pin executable and mode,
  • capture and rotate logs,
  • avoid uncontrolled auto-restarts during critical market windows. Production rollout pattern:
  1. Validate in simulation.
  2. Run constrained canary live session.
  3. Increase exposure only after expected behavior is confirmed.

Troubleshooting

Bot starts but no trades are placed

  • Check mode flags (--simulation vs --no-simulation).
  • Check market eligibility windows.
  • Confirm API and wallet permissions.
  • Verify thresholds are not too restrictive.

Unexpected strategy inactivity

  • Inspect detector parameters.
  • Confirm monitor receives real-time snapshots.
  • Check logs for guardrail-triggered skip conditions.

Backtest/live behavior diverges

  • Confirm same config parameters were used.
  • Validate timestamp alignment and dataset quality.
  • Recheck assumptions for slippage and fill behavior.

Security and Risk Controls

  • Never commit secrets or private keys.
  • Test every change in simulation first.
  • Use dedicated trading wallets.
  • Apply external notional and risk caps.
  • Keep auditable logs for all live sessions.
  • Define emergency stop procedures before scaling exposure.

Development Standards

  • Keep strategy logic in src/strategy.
  • Keep external integrations in src/connectors.
  • Keep side effects and sequencing in src/engine.
  • Keep binaries thin and orchestration-focused.
  • Prefer additive, testable, layer-aligned changes. Recommended engineering workflow:
  1. update strategy code,
  2. run simulation,
  3. run backtest,
  4. perform constrained live validation,
  5. promote after review.

Roadmap

  • Expand strategy plugin boundaries.
  • Improve structured runtime metrics.
  • Add more deterministic replay harness coverage.
  • Strengthen operational alerting hooks.

License

Use according to your repository and organizational licensing policy.

Releases

No releases published

Packages

 
 
 

Contributors

Languages