API · Budowa
Gotowe przepisy na rzeczy, których potrzebuje każdy bot Polymarket. Wszystko na CLOB V2 / pUSD, Python (odczyty nie wymagają klucza). Weź jeden, uruchom, idź dalej. Najpierw uruchom dowolny odczyt na żywo w piaskownicy:
tick_size rynku (zwykle "0.01", ale niektóre rynki mają "0.001") oraz, dla
wielowynikowych rynków „negative risk", neg_risk=True. Odczytaj oba z rynku przed podpisaniem -
błędna wielkość ticka lub brak flagi neg_risk kończy się odrzuceniem albo, gorzej, błędną wyceną. Przepis 3 pokazuje jak.1. Pobierz identyfikatory tokenów rynku ze sluga
Każda transakcja zaczyna się tutaj: na wejściu ludzki slug, na wyjściu dwa identyfikatory tokenów wyników.
import requests, json
m = requests.get("https://gamma-api.polymarket.com/markets",
params={"slug": SLUG}).json()[0]
outcomes = json.loads(m["outcomes"]) # ["Yes","No"]
token_ids = json.loads(m["clobTokenIds"]) # aligned with outcomes
yes_token = token_ids[outcomes.index("Yes")]
tick_size = m.get("orderPriceMinTickSize", "0.01") # use this, don't hardcode
neg_risk = bool(m.get("negRisk", False)) # needed for multi-outcome markets
2. Wyprowadź poświadczenia API (jednorazowo)
Handel wymaga klucza/sekretu/passphrase API wyprowadzonych z twojego klucza prywatnego. Wyprowadź raz, a potem przekazuj
creds każdemu klientowi - w V2 nie ma set_api_creds.
import os
from py_clob_client_v2 import ClobClient
boot = ClobClient(host="https://clob.polymarket.com", chain_id=137, key=os.environ["PK"])
creds = boot.create_or_derive_api_key() # idempotent: same key -> same creds
client = ClobClient(host="https://clob.polymarket.com", chain_id=137,
key=os.environ["PK"], creds=creds)
3. Odczytaj księgę i oszacuj poślizg
Przejdź po poziomach ask, by uzyskać realną średnią cenę realizacji przy kupnie (bid przy sprzedaży), zanim zaangażujesz wielkość.
book = client.get_order_book(token_id)
def cost_to_buy(book, shares):
rem, spent = shares, 0.0
for lvl in book.asks: # asks sorted best (lowest) first
take = min(rem, float(lvl.size)); spent += take*float(lvl.price); rem -= take
if rem <= 0: break
return (spent/shares, rem) # (avg fill price, unfilled shares)
4. Złóż i anuluj zlecenie z limitem (GTC)
from py_clob_client_v2 import (ClobClient, OrderArgs, OrderType,
PartialCreateOrderOptions, Side, OrderPayload)
resp = client.create_and_post_order(
order_args=OrderArgs(token_id=token_id, price=0.45, side=Side.BUY, size=100),
options=PartialCreateOrderOptions(tick_size=tick_size, neg_risk=neg_risk),
order_type=OrderType.GTC, # rests on the book until filled/cancelled
)
client.cancel_order(OrderPayload(orderID=resp["orderID"]))
5. Obejmij płynność teraz - zlecenie rynkowe (FOK)
Zlecenie rynkowe jest wyrażane w USDC, nie w udziałach, i realizuje się natychmiast albo anuluje. Użyj FOK, gdy musisz być zrealizowany w całości, FAK, by zrealizować, ile się da.
from py_clob_client_v2 import MarketOrderArgs
client.create_and_post_market_order(
order_args=MarketOrderArgs(token_id=token_id, amount=25.0, side=Side.BUY), # $25
options=PartialCreateOrderOptions(tick_size=tick_size, neg_risk=neg_risk),
order_type=OrderType.FOK,
)
6. Wylistuj, wyślij zbiorczo i anuluj zlecenia
orders = client.get_orders() # your resting orders
client.cancel_orders([o["orderID"] for o in orders]) # cancel a batch
client.cancel_all() # or wipe everything (panic button)
# Post several quotes in ONE request (POST /orders, max 15 per batch).
# post_only=True makes each strictly a maker order - it's rejected rather than
# allowed to cross the book, so you never accidentally pay the taker fee.
client.create_and_post_orders([
OrderArgs(token_id=token_id, price=0.44, side=Side.BUY, size=50),
OrderArgs(token_id=token_id, price=0.48, side=Side.SELL, size=50),
], options=PartialCreateOrderOptions(tick_size=tick_size, neg_risk=neg_risk, post_only=True))
7. Śledź pozycje i PnL dowolnego portfela (bez klucza)
import requests
for p in requests.get("https://data-api.polymarket.com/positions",
params={"user": PROXY_ADDRESS}).json():
print(p["title"], p["outcome"], "PnL", p["cashPnl"], p["percentPnl"])
8. Obserwuj swoje realizacje przez WebSocket
# wss://ws-subscriptions-clob.polymarket.com/ws/user (auth: api key/secret/passphrase)
# subscribe by condition_id; you get fills/cancels for your orders in real time.
# Send a PING every ~10s or the server drops you. Full reconnect+heartbeat pattern:
# /pl/api/polymarket-websocket/
9. Minimalny takt market makera
mid = float(client.get_midpoint(token_id)["mid"])
spread = 0.02 # quote 1 cent each side of mid
bid = round(mid - spread/2, 2); ask = round(mid + spread/2, 2) # round to tick
for price, side in [(bid, Side.BUY), (ask, Side.SELL)]:
client.create_and_post_order(
order_args=OrderArgs(token_id=token_id, price=price, side=side, size=50),
options=PartialCreateOrderOptions(tick_size=tick_size, neg_risk=neg_risk),
order_type=OrderType.GTC)
# reprice on every book update; makers pay 0 fees and can earn liquidity rewards.
Nowy projekt? Polymarket dostarcza teraz zunifikowane SDK (py-sdk / @polymarket/sdk),
które łączy API REST i WebSockety w jeden pakiet - warto rzucić okiem, gdy wyrośniesz z tych fragmentów.
Zobacz dobór SDK.
Dalej: Dokumentacja CLOB · Data API · Pomiń instalację - szablony startowe.



