BUHAY
$7.62 na kita bawat kalakalan ay iyo / bawat kalakalan
Kunin ang bot

Polymarket Gamma API tutorial

Walkthrough sa code para kumuha ng markets at events mula sa Polymarket Gamma API, kasama ang pagination, filtering, at best practices para sa mga developer.

Na-update 2026-04-20· 6 min
API
Polymarket
Gamma
developers

Polymarket Gamma API tutorial

Ang tutorial na ito sa Polymarket Gamma API ay nagtuturo kung paano kumuha ng markets at events mula sa Gamma surface ng Polymarket, mag-handle ng pagination, at mag-apply ng karaniwang mga filter. Ang mga halimbawa ay gumagamit ng curl at TypeScript para mai-integrate mo ang mga read sa mga bot, dashboard, o analytics pipeline.

Key takeaways

  • Ang base URL ng Gamma ay https://gamma-api.polymarket.com at hindi nangangailangan ng auth para sa mga read.
  • Gamitin ang /markets at /events endpoints na may cursor-based pagination gamit ang after_cursor; huwag gumamit ng offset.
  • Irespeto ang rate limits: /markets ay 300 req / 10 s; pinagsamang /markets + /events listing limit ay 900 req / 10 s. Ang kabuuang API limit ay 4000 req / 10 s.
  • I-filter gamit ang mga field tulad ng condition_ids, clob_token_ids, slug, at tag_id para paliitin ang payload at iwasang maabot ang limits.
  • Gumamit ng maliit na page sizes at exponential backoff para sa production clients.

1. Gamma basics: endpoints and limits

Ang Gamma read base URL ay:

https://gamma-api.polymarket.com

Mga endpoint na gagamitin mo sa tutorial na ito:

  • GET /markets — listahan ng market at single-market queries
  • GET /events — grouped events (kapaki-pakinabang para sa event-level metadata)

Mahalagang rate limits na dapat idisenyo sa paligid:

  • /markets: 300 requests bawat 10 segundo
  • /markets + /events listing combined: 900 requests bawat 10 segundo
  • Kabuuang Gamma API: 4000 requests bawat 10 segundo

Kung ang iyong client ay magpo-poll o magba-backfill ng malalaking dataset, i-batch at i-stagger ang mga request at irespeto ang mga limit na ito.

2. Fetching markets: minimal curl example

Isang minimal na request para ilista ang markets gamit ang default parameters:

curl "https://gamma-api.polymarket.com/markets"

Para kontrolin ang page size (limit) at ordering:

curl "https://gamma-api.polymarket.com/markets?limit=100&order=volume24hr&ascending=false"

Mga tala:

  • Ang maximum ng limit ay 1000. Default ay 20.
  • Tinatanggihan ng Gamma ang offset-based pagination (HTTP 422). Gamitin ang after_cursor para sa keyset pagination.

3. Cursor-based pagination (after_cursor)

Nagbabalik ang Gamma ng next_cursor sa mga listing responses. Gamitin ang value na iyon sa after_cursor para kunin ang susunod na pahina. Nasa ibaba ang halimbawa ng flow sa TypeScript.

TypeScript example (node-fetch or native fetch):

import fetch from 'node-fetch';

const BASE = 'https://gamma-api.polymarket.com';

type MarketsResponse = {
  markets: any[];
  next_cursor?: string | null;
};

async function fetchAllMarkets(limit = 200) {
  let cursor: string | undefined;
  const all: any[] = [];

  while (true) {
    const url = new URL('/markets', BASE);
    url.searchParams.set('limit', String(limit));
    if (cursor) url.searchParams.set('after_cursor', cursor);

    const res = await fetch(url.toString());
    if (!res.ok) throw new Error(`Gamma error ${res.status}`);

    const body: MarketsResponse = await res.json();
    all.push(...body.markets);

    if (!body.next_cursor) break;
    cursor = body.next_cursor;

    // small delay to avoid spike; tune for your rate budget
    await new Promise((r) => setTimeout(r, 100));
  }

  return all;
}

Mga best practice na ipinapakita:

  • Gamitin ang limit para kontrolin ang page size at network usage.
  • Irespeto ang next_cursor at huminto kapag wala na ito.
  • Magdagdag ng maliit na delay o backoff kapag malapit ka na sa rate limits.

4. Filtering and query parameters worth knowing

Sinusuportahan ng Gamma ang maraming query parameters. Pinaka-kapaki-pakinabang kapag gusto mo ng targeted reads:

  • slug, id, question_ids, condition_ids, clob_token_ids, market_maker_address — lahat ay arrays
  • closed (boolean), active, archived
  • tag_id — filter ayon sa kategorya
  • order — comma-separated fields gaya ng volume24hr, volume, liquidity, endDate
  • ascending — boolean (default true)

Halimbawa: kunin ang active markets sa isang tag, naka-order ayon sa 24h volume pababa:

curl "https://gamma-api.polymarket.com/markets?active=true&tag_id=123&order=volume24hr&ascending=false&limit=100"

Kapag kailangan mo lang ng partikular na markets, magpasa ng arrays para sa slug o id para paliitin ang payload at iwasang mag-list scan.

5. Events endpoint

Ang /events endpoint ay naggugrupo ng mga markets sa ilalim ng event-level metadata (halimbawa: "2026 Presidential Election" bilang isang event na may maraming market conditions).

Basic call:

curl "https://gamma-api.polymarket.com/events?limit=50"

Gumagamit din ang Events ng after_cursor para sa pagination at ibinabahagi ang combined listing limit sa /markets (900 req / 10 s para sa pinagsamang listings).

6. Practical TypeScript example: fetch markets by condition_ids

Ang halimbawang ito ay kumukuha ng markets para sa listahan ng condition IDs, na may concurrency control at exponential backoff.

import fetch from 'node-fetch';

const BASE = 'https://gamma-api.polymarket.com';

async function fetchMarketsByCondition(conditionIds: string[]) {
  const results: any[] = [];

  for (const id of conditionIds) {
    let cursor: string | undefined;
    let retries = 0;

    while (true) {
      const url = new URL('/markets', BASE);
      url.searchParams.set('limit', '200');
      url.searchParams.set('condition_ids', id);
      if (cursor) url.searchParams.set('after_cursor', cursor);

      const res = await fetch(url.toString());
      if (res.status === 429) {
        // respect rate limits with exponential backoff
        await new Promise((r) => setTimeout(r, 1000 * Math.pow(2, retries)));
        retries = Math.min(retries + 1, 5);
        continue;
      }

      if (!res.ok) throw new Error(`Gamma ${res.status}`);

      const body = await res.json();
      results.push(...body.markets);

      if (!body.next_cursor) break;
      cursor = body.next_cursor;
    }
  }

  return results;
}

Mga tala para sa production use:

  • Gumamit ng concurrency limiter (p-map, p-limit) kung malaki ang conditionIds.
  • I-cache ang hindi nagbabagong resulta (ETag/If-None-Match) kung sinusuportahan ng API para sa use case mo.
  • I-monitor ang request rate laban sa dokumentadong limits.

7. Common pitfalls and troubleshooting

  • Huwag gumamit ng offset — ibinabalik ng Gamma ang HTTP 422 para sa offset parameters.
  • Ang pag-request ng napakalaking pages nang walang cursors ay maaaring maabot ang rate limits at magdulot ng memory pressure; mas mabuting pumili ng mas maliit na limits at gumamit ng cursor traversal.
  • Ang pinagsamang /markets + /events listing limits ay nangangahulugang mabilis kang ma-throttle kung heavy ang polling sa parehong endpoints.
  • Nagbabalik ang API ng next_cursor para sa keyset pagination; ituring ito bilang opaque at ipasa ito nang literal pabalik.

8. Integrating with real-time data

Ang Gamma ay ang REST surface para sa metadata at historical listings. Para sa real-time order-book at tick events, gamitin ang Market WebSocket sa wss://ws-subscriptions-clob.polymarket.com/ws/market. Sinusuportahan ng WebSocket hanggang 500 instruments per connection at nag-eemit ng price_change, best_bid_ask, last_trade_price, at tick_size_change events.

Panatilihin ang REST para sa backfills at WebSocket para sa live updates.

9. How this affects your trading or tooling

Kung nagbuo ka ng trading bots, dashboard, o data pipelines, ang Gamma ang canonical read source para sa market metadata, tags, at listings. Gamitin ang cursor pagination, mag-filter nang agresibo, at i-pair ang Gamma reads sa CLOB API o Market WebSocket para sa presyo at order-book data. I-plan ang iyong polling cadence ayon sa dokumentadong rate limits para maiwasan ang throttling.

Gamma ay read-only para sa public data; walang kinakailangang API key para sa mga halimbawa sa itaas. Para sa order placement at book operations gamitin ang CLOB API sa https://clob.polymarket.com, na nangangailangan ng API key + HMAC.

Closing

Tinakpan ng Polymarket Gamma API tutorial na ito ang praktikal na mga hakbang para kumuha ng markets at events, mag-handle ng cursor pagination, at iwasan ang karaniwang pitfalls. Gamitin ang mga pattern na ito bilang batayan para sa maaasahang mga bot at analytics na nirerespeto ang Gamma rate limits at pagination model.

Frequently asked questions

Do I need an API key to read from the Gamma API?

Hindi. Ang public read endpoints ng Gamma ay hindi nangangailangan ng authentication. Ang base URL ay https://gamma-api.polymarket.com. Tanging ang CLOB endpoint ang nangangailangan ng API key + HMAC para sa trading.

How do I page through large market lists?

Gamitin ang cursor-based pagination. Bawat listing ay nagbabalik ng next_cursor; ipasa ang value na iyon bilang after_cursor para kunin ang susunod na page. Tinatanggihan ng Gamma ang offset-based pagination na may HTTP 422.

What are the important rate limits to consider?

/markets ay may limit na 300 requests bawat 10 segundo. Ang pinagsamang /markets + /events listing calls ay binibilang patungo sa 900 req / 10 s combined limit. Ang kabuuang Gamma API limit ay 4000 req / 10 s. I-stagger ang mga request at mag-implement ng backoff para iwasan ang throttling.

Should I use Gamma or the Market WebSocket for real-time data?

Gamitin ang Gamma para sa metadata, listings, at historical reads. Gamitin ang Market WebSocket (wss://ws-subscriptions-clob.polymarket.com/ws/market) para sa real-time order-book at tick events; sinusuportahan ng WebSocket hanggang 500 instruments per connection.

Can I filter markets by tag or condition?

Oo. Sinusuportahan ng Gamma ang mga filter tulad ng tag_id, condition_ids, clob_token_ids, slug, at iba pa. Ang pagpasa ng specific filters ay nagpapaliit ng payload at tumutulong manatili sa loob ng rate limits.

Kaugnay na mga gabay

Pang-edukasyon lamang. Hindi payong pinansyal, ligal, o ukol sa buwis. Maaaring hindi available ang Polymarket sa iyong hurisdiksyon.