Skip to content

arjunprakash027/Mantis

Repository files navigation

Mantis

Mantis is a high-performance market data collector and paper trading engine designed for Polymarket. It bridges the gap between Polymarket's global API/WebSocket infrastructure and local high-frequency trading systems by piping live data and simulated order execution into a low-latency Redis backend.

Architecture

Mantis is built in Go for speed and safety, utilizing a modular "One-Channel-Per-Stream" architecture. It runs multiple concurrent data pipelines:

  1. Global Discovery Engine: Periodically scans the entire exchange (pagination over ~28k+ active markets) to find the newest and most liquid opportunities.
  2. Smart Metadata Registry: Maps market slugs to underlying CLOB asset IDs and outcome names, allowing bots to perform discovery without hitting Polymarket APIs.
  3. High-Speed Ingestion: Maintains persistent WebSocket connections to the Polymarket CLOB for real-time L2 orderbook updates with automated heartbeats and fail-safe logging.
  4. Atomic Paper Executor: A high-fidelity trading simulator that executes orders against live orderbook prices using atomic Redis Lua scripts.

Current Progress

  • Full Exchange Discovery: Automated pagination to fetch and index all active markets.
  • Real-Time Paper Trading: Integrated execution engine that tracks balances, fills orders at live BBA (Best Bid/Offer), and maintains an audit log.
  • YAML-Based Management: Configure multiple markets and toggle discovery/orderbook pipelines via config.yaml.
  • Safe Execution: Implementation of strict price caching (no assumptions) and 60-second stale price guards to prevent trading on "zombie" data.
  • High-Performance Routing: Sub-millisecond distribution of WebSocket updates into namespaced Redis Streams.

Getting Started

Prerequisites

  • Go 1.21+
  • Redis (running locally on port 6379)
  • Python 3.x (for the sample order script)

Setup & Configuration

Mantis is managed via config.yaml. Add the market slugs you want to track to the orderbook.markets list.

pipelines:
  discovery:
    enabled: true
    interval_minutes: 10
  orderbook:
    enabled: true
    markets:
      - bitcoin-up-or-down-february-19-10am-et

Running the Engine

# 1. Start your local Redis
brew services start redis

# 2. Reset Database (Wipe everything to start fresh)
redis-cli FLUSHALL

# 3. Fund your paper trading account (Default is $0)
redis-cli HSET portfolio:balance USD 1000

# 4. Start Mantis
go run main.go

Paper Trading Guide

Mantis includes an Atomic Execution Engine. When you send a trade signal, it checks the local price cache (populated by the live WebSocket) and executes the trade only if the data is fresh and reliable.

1. Placing an Order

Use the included order.py script to send signals to the engine.

# Usage: python3 order.py <BUY/SELL> <TOKEN_ID> <AMOUNT>
python3 order.py BUY 538482956... 10

2. Managing your Account (Redis)

All portfolio data is stored in the portfolio:balance hash.

  • View Balance & Positions: redis-cli HGETALL portfolio:balance
  • Add Funds: redis-cli HINCRBYFLOAT portfolio:balance USD 500
  • Wipe Balance: redis-cli DEL portfolio:balance
  • View Trade History: redis-cli XRANGE trade:log - +
  • Wipe History: redis-cli DEL trade:log

3. Metadata Discovery (Redis)

Mantis automatically maps market slugs to the necessary technical IDs.

  • List All Tracked Markets: redis-cli KEYS slug:assets:*
  • Find Token IDs for a Market: redis-cli SMEMBERS slug:assets:<slug>
  • View Token Details (Outcome/Market Name): redis-cli HGETALL token:meta:<token_id>
  • Check Stream Volume: redis-cli XLEN orderbook:stream:<asset_id>

4. Execution Rules

  • No Assumptions: Orders are only filled if the engine has received an explicit best_bid or best_ask from the exchange.
  • Stale Guard: If a price hasn't been updated in 60 seconds, the executor will reject the trade to prevent "slippage" against dead data.
  • Atomic Fills: Using Lua scripts ensures that your balance update and trade logging happen as a single atomic unit—no partial fills or missed logs.

Data Schema

1. Global Discovery (Stream)

XREAD BLOCK 0 STREAMS discovery:stream:all $

  • Contains metadata for all 28k+ active markets.

2. Live Orderbook (Stream)

XREAD BLOCK 0 STREAMS orderbook:stream:<asset_id> $

  • Namespaced L2 updates for markets defined in your config.yaml.

3. Execution Signals (Streams)

  • Inbound Signals: signals:inbound (Format: {"action": "BUY", "asset": "ID", "amount": 1.0})
  • Outbound Results: signals:outbound (Contains fill price, timestamp, and any error messages).

Deployment

Mantis includes an automated deployment script (deploy.sh) to cross-compile and ship the binary to your remote VPS.

1. Prerequisite: SSH Alias

To use the script seamlessy, set up an SSH alias for your server. Open or create ~/.ssh/config on your Mac and add:

Host server-alias
    HostName <YOUR_SERVER_IP>
    User root
    IdentityFile ~/.ssh/id_ed25519

For more details on SSH config, see: Speed up SSH by using Aliases

2. Passwordless Login (Recommended)

Set up SSH keys so you don't have to type your password every time you deploy:

# Copy your local key to the server
ssh-copy-id server-alias

3. Running Deployment

The script handles Linux (AMD64) cross-compilation and file transfer via SCP.

# Make the script executable
chmod +x deploy.sh

# Build & Deploy
./deploy.sh

Examples (Python)

To help you get started with building bots on top of Mantis, check out the scripts/ directory.

1. Account Info (scripts/get_redis_information.py)

A comprehensive script that lists all tracked markets, their token IDs (with human names), and your current portfolio balance.

2. Orderbook Streamer (scripts/get_order_book.py)

A simple listener that connects to Redis and prints live Best Bid/Offer (BBO) updates as Mantis pushes them. Handles Polymarket batching and sorting automatically.

3. Random Trader (scripts/random_trader.py)

A simulated strategy that places random small BUY/SELL orders every few seconds to test your executor and portfolio logic.

How to run scripts:

cd scripts
pip install -r requirements.txt
python3 get_redis_information.py
python3 get_order_book.py <TOKEN_ID>

Note: The trading strategy implementations and execution modules remain internal and private (Simulated context).

About

Mantis is a event stream, streaming data from polymarket for all the trading bots that need it

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors