PolymarketPolymarketDeveloper22 min read2026-01-21

Polymarket Subgraph Queries: GraphQL Examples for Historical Data

AL - Founder of PolyTrack, Polymarket trader & analyst

AL

Founder of PolyTrack, Polymarket trader & analyst

Polymarket Subgraph Queries: GraphQL Examples for Historical Data - Developer Guide for Polymarket Traders | PolyTrack Blog

Polymarket's subgraph on The Graph network provides historical on-chain data via GraphQL, enabling you to query trades, positions, orderbook history, and market activity going back months or years. This comprehensive 2026 guide covers all available subgraphs, GraphQL query examples, schema documentation, and production-ready code patterns for accessing Polymarket's historical blockchain data.

Unlike the Gamma API which provides real-time market data, Polymarket subgraphs provide historical data indexed from on-chain transactions. This makes them perfect for backtesting strategies, analyzing historical trading patterns, building analytics dashboards, and researching market behavior over time. Understanding subgraph queries is essential for any developer building Polymarket analytics tools or historical research applications. Professional developers use enterprise platforms like PolyTrack Pro to access pre-built historical analytics and comprehensive trade history without building custom subgraph integrations from scratch.

🔑 Key Facts About Polymarket Subgraphs

  • • Network: The Graph protocol (decentralized indexing)
  • • Data Type: Historical on-chain transactions indexed from blockchain
  • • Access: Public GraphQL endpoints (no authentication required)
  • • Use Cases: Historical analysis, backtesting, analytics, research
  • • Limitations: Not real-time (indexed with delay), query complexity limits

What Are Polymarket Subgraphs?

Polymarket subgraphs are indexed databases of historical blockchain data hosted on The Graph protocol. They aggregate and organize on-chain transactions from Polymarket's smart contracts, making historical data easily queryable via GraphQL:

  • • Blockchain Indexing: The Graph indexes all Polymarket transactions from Ethereum/Polygon
  • • Data Organization: Transactions organized into logical entities (trades, positions, orders, markets)
  • • GraphQL Interface: Query data using GraphQL instead of parsing raw blockchain logs
  • • Historical Coverage: Access months or years of historical trading data
  • • Public Access: No authentication required, free public endpoints

Subgraphs vs Real-Time APIs

FeatureSubgraphsGamma API
Data TypeHistorical on-chainReal-time market data
Time RangeMonths/yearsCurrent snapshot
LatencyIndexed (delayed)Real-time (1-2s)
Use CaseHistorical analysis, backtestingLive trading, current prices
Query TypeGraphQLREST + GraphQL

Available Polymarket Subgraphs

Polymarket operates multiple subgraphs for different data types. Each subgraph focuses on a specific aspect of Polymarket data:

1. Orderbook Subgraph

Tracks orderbook snapshots, order placements, fills, and cancellations. Useful for analyzing order flow and market microstructure.

# Goldsky-hosted endpoint (commonly used)
https://api.goldsky.com/api/public/project_cl6mb8i9h0003e201j6li0diw/subgraphs/orderbook-subgraph/0.0.1/gn

# The Graph hosted endpoint
https://api.thegraph.com/subgraphs/name/polymarket/orderbook-subgraph

2. Positions Subgraph

Tracks wallet positions, position changes, and P&L over time. Essential for analyzing trader behavior and performance.

# Goldsky endpoint
https://api.goldsky.com/api/public/project_cl6mb8i9h0003e201j6li0diw/subgraphs/positions-subgraph/0.0.7/gn

3. Activity Subgraph

Tracks all trading activity including trades, deposits, withdrawals, and market events. Comprehensive activity feed.

# Goldsky endpoint
https://api.goldsky.com/api/public/project_cl6mb8i9h0003e201j6li0diw/subgraphs/activity-subgraph/0.0.4/gn

4. Open Interest Subgraph

Tracks open interest, liquidity, and market depth over time. Useful for analyzing market sentiment and capital flows.

# Goldsky endpoint
https://api.goldsky.com/api/public/project_cl6mb8i9h0003e201j6li0diw/subgraphs/oi-subgraph/0.0.6/gn

⚠️ Subgraph Endpoint Changes

Polymarket subgraph endpoints may change over time. Goldsky-hosted endpoints are commonly used and updated. Always check official Polymarket documentation or The Graph explorer for current endpoint URLs. Some subgraphs may require authentication or have rate limits.

See What Whales Are Trading Right Now

Get instant alerts when top traders make moves. Track P&L, win rates, and copy winning strategies.

Track Whales Free

Free forever. No credit card required.

Basic GraphQL Query Structure

All Polymarket subgraphs use standard GraphQL query syntax. Here's the basic structure:

query QueryName($variable: Type) {
  entityName(
    where: { field: $variable }
    orderBy: timestamp
    orderDirection: desc
    first: 100
    skip: 0
  ) {
    id
    field1
    field2
    nestedEntity {
      nestedField
    }
  }
}

Common Query Parameters

  • • where: Filter conditions (e.g., where: { token: "0x..." })
  • • orderBy: Field to sort by (usually timestamp, price, amount)
  • • orderDirection: asc or desc
  • • first: Maximum number of results (limit)
  • • skip: Number of results to skip (for pagination)

Common Subgraph Queries

Query 1: Historical Trades by Wallet

Get all trades executed by a specific wallet address:

query GetWalletTrades($wallet: String!) {
  trades(
    where: { user: $wallet }
    orderBy: timestamp
    orderDirection: desc
    first: 1000
  ) {
    id
    token
    amount
    price
    timestamp
    side
    user
  }
}

# Variables:
# {
#   "wallet": "0x1234..."
# }

Query 2: Market Volume Over Time

Analyze trading volume for a specific market (condition ID) over time:

query GetMarketVolume($conditionId: String!) {
  trades(
    where: { conditionId: $conditionId }
    orderBy: timestamp
    orderDirection: asc
    first: 10000
  ) {
    timestamp
    amount
    price
    side
  }
}

# Variables:
# {
#   "conditionId": "0xabcd..."
# }

Query 3: Position Snapshots

Get position history for a wallet across all markets:

query GetPositionHistory($wallet: String!) {
  positions(
    where: { user: $wallet }
    orderBy: timestamp
    orderDirection: desc
    first: 500
  ) {
    id
    token
    balance
    timestamp
    user
  }
}

# Variables:
# {
#   "wallet": "0x1234..."
# }

Query 4: Orderbook History

Retrieve historical orderbook snapshots for a specific token:

query GetOrderbookHistory($token: String!) {
  orderbookSnapshots(
    where: { token: $token }
    orderBy: timestamp
    orderDirection: desc
    first: 100
  ) {
    id
    timestamp
    bids {
      price
      amount
    }
    asks {
      price
      amount
    }
  }
}

# Variables:
# {
#   "token": "0xef01..."
# }

đź’ˇ Skip Building Subgraph Infrastructure

Building comprehensive historical analytics from subgraphs requires significant engineering: GraphQL query optimization, pagination handling, data aggregation, and performance tuning. PolyTrack Pro provides pre-built historical analytics, comprehensive trade history, and position tracking across thousands of wallets—all without building custom subgraph integrations. Access months of indexed data via our API without query complexity limits.

Focus on analysis, not infrastructure. Try PolyTrack Pro free for 3 days - no credit card required.

Python Example: Query Subgraph

Here's a complete Python example using the gql library:

from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport

# Configure transport
transport = RequestsHTTPTransport(
    url="https://api.goldsky.com/api/public/project_cl6mb8i9h0003e201j6li0diw/subgraphs/positions-subgraph/0.0.7/gn"
)

client = Client(transport=transport, fetch_schema_from_transport=True)

# Define query
query = gql("""
  query GetPositions($wallet: String!) {
    positions(
      where: { user: $wallet }
      orderBy: timestamp
      orderDirection: desc
      first: 100
    ) {
      id
      token
      balance
      timestamp
    }
  }
""")

# Execute query
variables = {"wallet": "0x1234..."}
result = client.execute(query, variable_values=variables)

# Process results
for position in result['positions']:
    print(f"Token: {position['token']}, Balance: {position['balance']}")

JavaScript Example: Query Subgraph

Node.js example using graphql-request:

import { request, gql } from 'graphql-request';

const SUBGRAPH_URL = 'https://api.goldsky.com/api/public/project_cl6mb8i9h0003e201j6li0diw/subgraphs/orderbook-subgraph/0.0.1/gn';

const query = gql`
  query GetTrades($token: String!) {
    trades(
      where: { token: $token }
      orderBy: timestamp
      orderDirection: desc
      first: 100
    ) {
      id
      amount
      price
      timestamp
      user
    }
  }
`;

async function getTrades(token) {
  const variables = { token };
  const data = await request(SUBGRAPH_URL, query, variables);
  return data.trades;
}

// Usage
const trades = await getTrades('0xabcd...');
console.log(`Found ${trades.length} trades`);

Pagination and Large Queries

Subgraphs have query limits (typically 1000 results per query). For larger datasets, use pagination:

async function getAllTrades(wallet, batchSize = 1000) {
  let allTrades = [];
  let skip = 0;
  let hasMore = true;

  while (hasMore) {
    const query = gql`
      query GetTrades($wallet: String!, $skip: Int!) {
        trades(
          where: { user: $wallet }
          orderBy: timestamp
          orderDirection: desc
          first: ${batchSize}
          skip: $skip
        ) {
          id
          amount
          price
          timestamp
        }
      }
    `;

    const variables = { wallet, skip };
    const data = await request(SUBGRAPH_URL, query, variables);
    
    allTrades.push(...data.trades);
    
    if (data.trades.length < batchSize) {
      hasMore = false;
    } else {
      skip += batchSize;
    }
  }

  return allTrades;
}

Rate Limits and Best Practices

Rate Limiting

Subgraph endpoints may have rate limits:

  • • Query Complexity: Complex queries with many nested fields may be rate-limited
  • • Request Frequency: Too many requests per second may trigger limits
  • • Solution: Implement exponential backoff and batch queries when possible

Optimization Tips

  • • Request only needed fields: Don't query unnecessary data
  • • Use filters: Apply where clauses to reduce results
  • • Limit result size: Use first parameter appropriately
  • • Cache results: Historical data doesn't change, cache aggressively
  • • Batch queries: Combine multiple queries into single requests when possible

🚀 Access Pre-Built Historical Analytics

Building comprehensive historical analytics from subgraphs requires months of engineering: query optimization, pagination, aggregation, and performance tuning. PolyTrack Pro provides pre-built historical analytics, comprehensive trade history across thousands of wallets, position tracking over time, and advanced filtering—all accessible via API without query complexity limits or rate limit management.

Skip building subgraph infrastructure and focus on insights. Start your free 3-day trial - no credit card required.

Conclusion

Polymarket subgraphs provide powerful access to historical on-chain data via GraphQL, enabling backtesting, analytics, and research. Understanding how to query subgraphs effectively opens up extensive historical datasets for analysis.

While subgraphs are powerful, building production-grade historical analytics requires significant engineering. Consider using pre-built analytics platforms like PolyTrack Pro for comprehensive historical data access without the complexity of managing subgraph queries, pagination, and rate limits yourself.

Related Resources

Frequently Asked Questions

Polymarket subgraphs are indexed databases of historical blockchain data hosted on The Graph protocol. They aggregate on-chain transactions from Polymarket's smart contracts, making historical trading data easily queryable via GraphQL for analysis, backtesting, and research.

12,400+ TRADERS

Stop Guessing. Start Following Smart Money.

Get instant alerts when whales make $10K+ trades. Track P&L, win rates, and copy winning strategies.

Track Whales FreeNo credit card required