All packages

polymarket_orderbook_substreams

PaulieB14
This is not the latest version — go to v0.4.0
v0.2.0/99K downloads/Repository

Package ref

polymarket-orderbook-substreams@v0.2.0

Run package

CLI

Run map_ctf_exchange_orders_matched from the command line.

substreams run polymarket-orderbook-substreams@v0.2.0 map_ctf_exchange_orders_matched -e polygon --start-block -1
Authenticate by running substreams auth or directly on thegraph.market (see docs).

README

Polymarket

Polymarket Orderbook Substreams

Real-time orderbook analytics for Polymarket prediction markets on Polygon

Substreams Package Polygon License PostgreSQL Clickhouse


Overview

High-performance Substreams modules for extracting, processing, and persisting orderbook events from Polymarket's CTF Exchange and Neg Risk Exchange contracts on Polygon. Built with foundational stores for efficient parallel execution and includes ready-to-use SQL and Clickhouse sinks.

Key Features

FeatureDescription
Dual Exchange SupportTracks both CTF Exchange and Neg Risk Exchange contracts
Order Fill EventsDetailed trade execution data with price calculations
Market AnalyticsVolume, trades, buy/sell ratios, average trade sizes
Trader AnalyticsPer-trader volume, trade counts, activity tracking
Global StatisticsPlatform-wide metrics and fee revenue
PostgreSQL SinkReady-to-use SQL schema for relational queries
Clickhouse SinkHigh-performance analytics with materialized views

Quick Start

Installation

# Install Substreams CLI
brew install streamingfast/tap/substreams

# Authenticate
substreams auth

Run Streaming Modules

# Stream all order fills from both exchanges
substreams run https://spkg.io/PaulieB14/polymarket-orderbook-substreams-v0.2.0.spkg \
  map_all_order_fills \
  -e polygon.substreams.pinax.network:443 \
  -s 57000000 -t +1000

# Stream market analytics
substreams run https://spkg.io/PaulieB14/polymarket-orderbook-substreams-v0.2.0.spkg \
  map_market_orderbooks \
  -e polygon.substreams.pinax.network:443 \
  -s 57000000 -t +1000

# Stream global platform stats
substreams run https://spkg.io/PaulieB14/polymarket-orderbook-substreams-v0.2.0.spkg \
  map_global_orderbook_stats \
  -e polygon.substreams.pinax.network:443 \
  -s 57000000 -t +1000

Architecture

                              Polygon Blockchain
                                     │
                                     ▼
                            ┌─────────────────┐
                            │ Firehose Blocks │
                            └─────────────────┘
                                     │
                    ┌────────────────┴────────────────┐
                    ▼                                 ▼
        ┌───────────────────┐             ┌───────────────────┐
        │   CTF Exchange    │             │  Neg Risk Exchange│
        │ Order Fill Events │             │  Order Fill Events│
        └───────────────────┘             └───────────────────┘
                    │                                 │
                    └────────────┬────────────────────┘
                                 ▼
                    ┌────────────────────────┐
                    │   map_all_order_fills  │
                    │  (Combined Event Stream)│
                    └────────────────────────┘
                                 │
            ┌────────────────────┼────────────────────┐
            ▼                    ▼                    ▼
   ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐
   │  store_markets  │  │  store_traders  │  │store_global_stats│
   │ (Market Stats)  │  │ (Trader Stats)  │  │ (Platform Stats) │
   └─────────────────┘  └─────────────────┘  └─────────────────┘
            │                    │                    │
            ▼                    ▼                    ▼
   ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐
   │map_market_      │  │map_trader_      │  │map_global_      │
   │orderbooks       │  │accounts         │  │orderbook_stats  │
   └─────────────────┘  └─────────────────┘  └─────────────────┘
            │                    │                    │
            └────────────────────┼────────────────────┘
                                 ▼
                    ┌────────────────────────┐
                    │        db_out          │
                    │   (SQL/Clickhouse)     │
                    └────────────────────────┘
                                 │
                    ┌────────────┴────────────┐
                    ▼                         ▼
           ┌─────────────────┐      ┌─────────────────┐
           │   PostgreSQL    │      │   Clickhouse    │
           └─────────────────┘      └─────────────────┘

Modules

Layer 1: Event Extraction

ModuleDescription
map_ctf_exchange_order_filledExtracts OrderFilled events from CTF Exchange
map_neg_risk_exchange_order_filledExtracts OrderFilled events from Neg Risk Exchange
map_ctf_exchange_orders_matchedExtracts OrdersMatched events from CTF Exchange
map_neg_risk_exchange_orders_matchedExtracts OrdersMatched events from Neg Risk Exchange

Layer 1.5: Combined Events

ModuleDescription
map_all_order_fillsCombines order fills from both exchanges into unified stream

Layer 2: Foundational Stores

StoreKey PatternDescription
store_marketsmarket:{asset_id}Market-level statistics (volume, trades, prices)
store_traderstrader:{address}Trader analytics (volume, trade count, fees)
store_global_statsglobalPlatform-wide metrics

Layer 3: Analytics Outputs

ModuleDescription
map_market_orderbooksReal-time market snapshots on updates
map_trader_accountsTrader account updates for leaderboards
map_global_orderbook_statsGlobal platform statistics
map_orderbook_analyticsComprehensive analytics combining all stores

Layer 4: Database Sinks

ModuleDescription
db_outPostgreSQL sink with normalized tables
clickhouse_outClickhouse sink optimized for analytics

SQL Sink (PostgreSQL)

Setup

# Create database
createdb polymarket_orderbook

# Apply schema
psql -d polymarket_orderbook -f schema.sql

# Setup sink
substreams-sink-sql setup \
  "psql://user:pass@localhost:5432/polymarket_orderbook?sslmode=disable" \
  https://spkg.io/PaulieB14/polymarket-orderbook-substreams-v0.2.0.spkg

# Run sink
substreams-sink-sql run \
  "psql://user:pass@localhost:5432/polymarket_orderbook?sslmode=disable" \
  https://spkg.io/PaulieB14/polymarket-orderbook-substreams-v0.2.0.spkg \
  -e polygon.substreams.pinax.network:443

Example Queries

-- Top markets by volume
SELECT * FROM top_markets_by_volume;

-- Top traders by volume
SELECT * FROM top_traders_by_volume;

-- Recent large trades (> 1000 USDC)
SELECT * FROM recent_large_trades;

-- Market activity over time
SELECT
  DATE(created_at) as date,
  COUNT(*) as trades,
  SUM(taker_amount_filled::numeric / 1e18) as volume
FROM order_fills
GROUP BY DATE(created_at)
ORDER BY date DESC;

Clickhouse Sink

Setup

# Create database
clickhouse-client -q "CREATE DATABASE polymarket_orderbook"

# Apply schema
clickhouse-client -d polymarket_orderbook < clickhouse-schema.sql

# Setup sink
substreams-sink-sql setup \
  "clickhouse://default:@localhost:9000/polymarket_orderbook" \
  https://spkg.io/PaulieB14/polymarket-orderbook-substreams-v0.2.0.spkg

# Run sink
substreams-sink-sql run \
  "clickhouse://default:@localhost:9000/polymarket_orderbook" \
  https://spkg.io/PaulieB14/polymarket-orderbook-substreams-v0.2.0.spkg \
  -e polygon.substreams.pinax.network:443

Example Queries

-- Top markets by 24h volume
SELECT
    market_id,
    sum(total_volume) as volume_24h,
    sum(trades_count) as trades_24h
FROM hourly_volume
WHERE hour >= now() - INTERVAL 24 HOUR
GROUP BY market_id
ORDER BY volume_24h DESC
LIMIT 10;

-- Trader leaderboard
SELECT
    id,
    total_volume,
    trades_quantity,
    total_fees
FROM trader_analytics FINAL
WHERE is_active = 1
ORDER BY total_volume DESC
LIMIT 100;

-- Hourly volume trend
SELECT
    hour,
    sum(total_volume) as volume,
    sum(trades_count) as trades
FROM hourly_volume
WHERE hour >= now() - INTERVAL 7 DAY
GROUP BY hour
ORDER BY hour;

Data Schema

OrderFilledEvent

FieldTypeDescription
idstringUnique event identifier
transaction_hashstringTransaction hash
order_hashstringOrder hash
makerstringMaker address
takerstringTaker address
maker_asset_idstringMaker's asset token ID
taker_asset_idstringTaker's asset token ID
maker_amount_filledstringAmount filled for maker
taker_amount_filledstringAmount filled for taker
feestringTransaction fee
sidestringTrade side (buy/sell)
pricestringCalculated execution price
block_numberuint64Block number

MarketOrderbook

FieldTypeDescription
idstringMarket identifier
trades_quantityuint64Total trade count
buys_quantityuint64Buy trade count
sells_quantityuint64Sell trade count
collateral_volumestringTotal volume
average_trade_sizestringAverage trade size
total_feesstringTotal fees collected
mid_pricestringCurrent mid price

Contract Addresses

ContractAddressDescription
CTF Exchange0x4bfb41d5b3570defd03c39a9a4d8de6bd8b8982eMain prediction market exchange
Neg Risk Exchange0xC5d563A36AE78145C45a50134d48A1215220f80aNegative risk market exchange

Using as a Dependency

Import this package to build higher-level analytics:

# substreams.yaml
imports:
  polymarket: https://spkg.io/PaulieB14/polymarket-orderbook-substreams-v0.2.0.spkg

modules:
  - name: my_analytics_module
    kind: map
    inputs:
      - map: polymarket:map_all_order_fills
    output:
      type: proto:my.custom.Analytics

Build from Source

# Clone repository
git clone https://github.com/PaulieB14/polymarket-orderbook-substreams
cd polymarket-orderbook-substreams

# Build
substreams build

# Run locally
substreams run substreams.yaml map_all_order_fills \
  -e polygon.substreams.pinax.network:443 \
  -s 57000000 -t +100

Performance

MetricValue
Start Block57,000,000 (Polymarket launch)
Parallel ExecutionOptimized with foundational stores
LatencyLow latency with direct event extraction
Sink SupportPostgreSQL, Clickhouse

Related Projects


License

MIT License - see LICENSE for details.


Built for the Polymarket community
Powered by StreamingFast Substreams

Modules

Execution graph

11 modules