पॉलीमार्केट Bot ट्यूटोरियल · अध्याय 8 / 32

Bots के लिए पॉलीमार्केट CLOB API: order book snapshots के लिए REST endpoints, real-time updates के लिए WebSocket subscriptions, bids/asks parsing, mid-price और depth की computation, code samples.

इस chapter में क्या कवर किया गया है

CLOB API वह जगह है जहाँ orders sign होते हैं, भेजे जाते हैं, match होते हैं, और जहाँ order book रहता है। पॉलीमार्केट की दो SDK generations हैं - deprecated v1 और current v2। यह chapter केवल v2 को कवर करता है; 2026 में आप जो भी bot ship करें उसमें v1 नहीं होना चाहिए। हम REST snapshot path, WebSocket update channel, parsing details जो नए builders को फँसा देते हैं, और reconnect logic को कवर करते हैं - जिसके बिना एक long-running bot कुछ घंटों में sync से बाहर हो जाता है।

  • CLOB v1 vs v2 (use v2]
  • Order book REST snapshot
  • WebSocket subscriptions: market और user channels
  • bids/asks/depth parse करना
  • mid-price और best-bid/ask compute करना
  • Maker fees, taker fees, rebates
  • Code: WS connect करें और price-change events process करें
  • Reconnect और gap-handling

CLOB v1 vs v2 (use v2]

पॉलीमार्केट दो SDK generations maintain करता है। v1 (@polymarket/clob-client on npm, py-clob-client <0.30) deprecated है और 2024 में जोड़े गए कई order types missing हैं। v2 (@polymarket/clob-client-v2 Node में v1.0.2, Python में py-clob-client 0.34.6+) current standard है।

तीन concrete differences। v2 multi-outcome markets के लिए negRisk flag support करता है - NegRisk exchange के late 2024 में launch होने के बाद से यह required है। v2 WebSocket message shapes के लिए TypeScript types ship करता है; v1 any return करता है। v2 अगस्त 2025 के Gnosis Safe signature flow को natively handle करता है; v1 को custom signing glue की ज़रूरत होती है।

इस chapter का बाकी हिस्सा पूरे time v2 मानकर लिखा गया है। अगर आपको किसी पुराने tutorial में v1 code दिखे, तो जब तक साबित न हो कि वह सही है, उसे broken मानें - खासकर NegRisk markets के against order placement v1 में silently wrong exchange contract पर route हो सकता है।

Order book REST snapshot

REST snapshot endpoint किसी एक token के लिए एक point in time पर पूरा book return करता है।

GET https://clob.polymarket.com/book?token_id=<ERC1155_TOKEN_ID>

Response shape:

{
  "market": "0x...",
  "asset_id": "5413...",
  "timestamp": "1715600000000",
  "hash": "0x...",
  "bids": [{"price":"0.45","size":"120"}, {"price":"0.44","size":"380"}, ...],
  "asks": [{"price":"0.47","size":"85"}, {"price":"0.48","size":"210"}, ...]
}

Prices strings के रूप में 2-3 decimal places के साथ होते हैं; sizes strings होते हैं जो share counts represent करते हैं (dollars नहीं)। Bids high-to-low sorted होते हैं, asks low-to-high। hash एक deduplication marker है - unchanged book के repeated polls same hash return करते हैं और आपका bot processing skip कर सकता है।

REST snapshot one-off lookups के लिए सही choice है (entry decision पर price check)। Continuous monitoring के लिए नीचे दिया गया WebSocket channel use करें।

WebSocket subscriptions: market और user channels

दो WebSocket channels महत्वपूर्ण हैं।

Market channel: wss://ws-subscriptions-clob.polymarket.com/ws/market. एक या कई tokens subscribe करें; जैसे ही updates आते हैं, order-book updates receive करें।

{"type":"Market","markets":["0xCondId1","0xCondId2"]}

Messages हर change पर आते हैं। Types में book (full snapshot), price_change (delta), tick_size_change (rare), और last_trade_price (most recent fill) शामिल हैं।

User channel: wss://ws-subscriptions-clob.polymarket.com/ws/user. Authenticated; अपने order events receive करें - fills, partial fills, cancellations।

{"type":"User","auth":{"apiKey":"...","secret":"...","passphrase":"..."}}

Fill detect करने का सबसे साफ़ तरीका user channel है। Orders REST endpoint poll करना ज़्यादा costly है और polls के बीच state changes miss कर सकता है; WebSocket event उसी moment push करता है जब matcher उसे acknowledge करता है।

bids/asks/depth parse करना

Order book aggregated size के साथ price levels की list होता है। सही करने के लिए दो parsing conventions हैं।

Order direction: bids buy orders होते हैं (कोई इस price पर BUY करना चाहता है)। जब आपका bot SELL करता है, तो आप bid hit करते हैं। जब आपका bot BUY करता है, तो आप ask lift करते हैं। पॉलीमार्केट UI वही direction दिखाता है; कुछ दूसरे exchanges इसे उल्टा करते हैं।

Sorting: bids descending order में आते हैं (best bid first)। asks ascending order में आते हैं (best ask first)। Best bid bids[0] है; best ask asks[0] है। ध्यान रहे: public WebSocket कभी-कभी partial book updates भेजता है जो पहले से pre-sorted नहीं होते - किसी भी merge के बाद हमेशा defensively re-sort करें।

किसी level पर depth का मतलब transactable dollar value है: price * size. Top-5-level depth एक common liquidity metric है: sum(b.price * b.size for b in bids[:5]). अगर top-5 depth $100 से कम है, तो book illiquid है और ज़्यादातर strategy assumptions टूट जाती हैं।

mid-price और best-bid/ask compute करना

तीन derived price points जिनकी आपके bot को ज़रूरत होती है।

  • Best bid / best ask: bids[0].price और asks[0].price. वे prices जिन पर आप सचमुच trade कर सकते हैं, एक share के लिए।
  • Mid-price: (best_bid + best_ask) / 2. spread का mathematical center। valuation के लिए उपयोगी; आप mid पर trade नहीं करते।
  • VWAP price for size N: book को तब तक walk करें जब तक cumulative size N तक न पहुँच जाए, फिर size-weighted average price return करें। अभी N shares खरीदने की actual cost, deeper levels में sweep को account करते हुए।

Edge case: bid या ask side का खाली होना (कोई बेच नहीं रहा, या कोई खरीद नहीं रहा) मतलब book one-sided है। पॉलीमार्केट की market structure में यह resolved या near-resolved markets में होता है जहाँ एक side 0.999 पर होती है और loser side पर कोई liquidity offer नहीं करता। best-bid = 0 या best-ask = 1 को "do not trade" signals की तरह treat करें।

Maker fees, taker fees, rebates

पॉलीमार्केट maker-taker fee model चलाता है। May 2026 तक numbers:

  • Taker fee: 0 (zero) - existing book liquidity को lift करने वाले orders पर कोई fee नहीं लगती। ध्यान दें कि proxy operations पर gas / network costs लागू होते हैं।
  • Maker rebate: छोटा positive, programmatic, eligible reward-program markets में filled rested order के हिसाब से paid out। सभी markets में rewards नहीं होते।
  • NegRisk markets: same fee structure लेकिन अलग exchange contract पर; rewards अलग से accrue होते हैं।

Zero taker fee पॉलीमार्केट को traditional CFD venues से काफ़ी अलग बनाती है - trading का ज़्यादातर "cost" खुद bid-ask spread होता है, कोई explicit fee नहीं। जो strategy हर trade पर spread cross करती है, उसके लिए spread tax असली cost है; typical books पर round-trip 1-3 cents मानें, illiquid ones पर इससे ज़्यादा।

Maker rebates तभी chase करने लायक हैं जब liquidity-rewards-eligible markets आपकी strategy ideas से match हों। Chapter 19 liquidity-rewards farming को एक dedicated approach के रूप में कवर करता है।

Code: WS connect करें और price-change events process करें

Minimal Node example: connect करें, subscribe करें, एक token के लिए हर price-change event log करें।

import WebSocket from "ws";
const ws = new WebSocket("wss://ws-subscriptions-clob.polymarket.com/ws/market");
ws.on("open", () => {
  ws.send(JSON.stringify({ type: "Market", markets: ["<CONDITION_ID>"] }));
});
ws.on("message", (data) => {
  const msg = JSON.parse(data.toString());
  if (msg.event_type === "price_change") {
    console.log("price_change", msg.asset_id, msg.changes);
  } else if (msg.event_type === "book") {
    console.log("book snapshot", msg.bids?.[0], msg.asks?.[0]);
  }
});
ws.on("close", () => console.log("closed"));
ws.on("error", (e) => console.error("err", e.message));

एक WebSocket connection पर लगभग 30 tokens तक subscribe करना आराम से संभव है। इससे आगे जाएँ तो multiple connections में split करें - server कभी-कभी बड़ी subscriptions को बिना error दिए drop कर देता है, जिससे silent stale book reads होते हैं।

Reconnect और gap-handling

Long-running WebSocket connection drop होगा। Cloudflare कुछ घंटों में connections cycle करता है; networks blink करते हैं; पॉलीमार्केट कभी-कभी deploy करता है। इसके लिए plan करें।

Reconnect strategy: close या error पर jitter के साथ min(2^attempt, 30) seconds wait करें, फिर re-subscribe करें। Reconnect के बाद पहला successful message आते ही attempt counter reset कर दें।

Gap handling, reconnect speed से ज़्यादा महत्वपूर्ण है। जब WebSocket disconnected था, book move हो चुका था। हर reconnect पर, अपने हर subscribed token का REST snapshot दोबारा fetch करें और reconcile करें: जिन open positions का book meaningful रूप से बदल चुका है, उनकी state re-check की ज़रूरत होती है, exits fire करने पड़ सकते हैं, alarms stale हो सकते हैं। "मैंने 30 seconds के book updates miss कर दिए" वाला case लंबे समय तक चलने वाले bots का silent killer है - वे stale state पर चलते रहते हैं और ऐसे prices पर orders place करते हैं जो अब मौजूद ही नहीं हैं।

Defensive pattern: WebSocket state से independent होकर हर minute हर subscribed book का snapshot लें, और WS को snapshot poll के ऊपर fast-path optimization की तरह treat करें।

अक्सर पूछे जाने वाले प्रश्न

पॉलीमार्केट CLOB API endpoint क्या है?
Base CLOB endpoint https://clob.polymarket.com (REST) और wss://ws-subscriptions-clob.polymarket.com/ws/market (WebSocket) है। ये V2 endpoints हैं जिनका उपयोग @polymarket/clob-client-v2 और py-clob-client करते हैं।
Order book पढ़ने के लिए क्या मुझे API key चाहिए?
नहीं। Order book reads (snapshots और WebSocket subscriptions) public हैं और authentication की ज़रूरत नहीं होती। API key केवल orders place/cancel करने और account-specific data (positions, fills) पढ़ने के लिए चाहिए।
CLOB WebSocket price updates कितनी तेज़ी से push करता है?
जितनी तेज़ी से orders match होते हैं। Active markets में updates हर कुछ सौ milliseconds में आते हैं; thin markets केवल actual orders पर update होते हैं। Depth changes और trade events दोनों same WS channel से flow होते हैं - हर event type को सही तरह handle करने के लिए उसे parse करें।
पॉलीमार्केट order book का mid-price कैसे compute करूँ?
mid = (best_bid + best_ask) / 2 अगर दोनों मौजूद हों; वरना fallback के रूप में last_trade_price का use करें। Thin books में सावधान रहें जहाँ best_bid, best_ask से बहुत नीचे हो - mid meaningless हो सकता है। Mid को fair price मानने से पहले हमेशा spread भी consider करें।
2026 में पॉलीमार्केट पर maker fee क्या है?
ज़्यादातर categories में 0%। Makers को taker fees के 20-25% के बराबर rebates मिलते हैं। Taker fees category के हिसाब से बदलती हैं: sports 0.75%, politics 1.00%, economics 1.25%, crypto 1.80%। rebate-vs-fee asymmetry की वजह से active bots लगभग हमेशा market orders की बजाय limit orders के साथ quote करते हैं।
WebSocket disconnects को कैसे handle करूँ?
Exponential backoff (1s, 2s, 4s, max 30s) के साथ reconnect करें, same markets पर re-subscribe करें, और gap भरने के लिए REST snapshot दोबारा fetch करें। कभी भी stale order book पर भरोसा न करें - अगर आप 5 seconds से ज़्यादा disconnected रहे हैं, तो orders place करने से पहले fresh snapshot मांगें।