API · 빌드

모든 폴리마켓 봇에 필요한 것들을 복사해 쓰는 레시피입니다. 전부 CLOB V2 / pUSD, Python이며(읽기에는 키가 필요 없습니다) 하나 가져다 실행하고 넘어가면 됩니다. 읽기 작업은 먼저 샌드박스에서 실시간으로 실행해 보세요:

주문을 조용히 망가뜨리는 두 가지 설정. 모든 주문에는 시장의 올바른 tick_size(보통 "0.01"이지만 일부 시장은 "0.001")가 필요하고, 다중 결과 "네거티브 리스크" 시장에는 neg_risk=True가 필요합니다. 서명하기 전에 둘 다 시장에서 읽어 오세요. 잘못된 틱 사이즈나 빠진 neg_risk 플래그는 거부되거나, 더 나쁘게는 잘못된 가격으로 처리됩니다. 레시피 3에서 방법을 보여줍니다.

1. 슬러그로 시장의 토큰 ID 얻기

모든 거래는 여기서 시작합니다. 사람이 읽는 슬러그를 넣으면 두 개의 결과 토큰 ID가 나옵니다.

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. API 자격 증명 파생(한 번만)

거래에는 개인 키에서 파생한 API 키/시크릿/패스프레이즈가 필요합니다. 한 번 파생한 다음 모든 클라이언트에 creds를 전달하세요. V2에는 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. 호가창 읽기 & 슬리피지 추정

수량을 확정하기 전에 매도 호가를 훑어 매수의 실제 평균 체결가(매도라면 매수 호가)를 구하세요.

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. 지정가 주문 넣기 & 취소(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. 지금 유동성 가져가기 - 시장가 주문(FOK)

시장가 주문은 지분이 아니라 USDC 단위로 수량을 정하며, 즉시 체결되거나 취소됩니다. 전량 체결이 반드시 필요하면 FOK를, 가능한 만큼 체결하려면 FAK를 사용하세요.

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. 주문 조회, 일괄 등록, 취소

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. 임의 지갑의 포지션 & 손익 추적(키 불필요)

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. 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:
#   /en/api/polymarket-websocket/

9. 최소한의 마켓 메이커 틱

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.
실거래 주문 전에: 담보는 pUSD여야 하고, pUSD와 조건부 토큰을 세 개의 V2 거래소 컨트랙트에 한 번 승인해야 합니다(허용량 오류 해결 참고). 체결과 손익이 기대와 맞을 때까지는 기본적으로 페이퍼 모드를 사용하세요.

새 프로젝트인가요? 폴리마켓은 이제 REST API와 WebSocket을 하나의 패키지로 묶은 통합 SDK (py-sdk / @polymarket/sdk)를 제공합니다. 이 예제들을 넘어설 때쯤 살펴볼 만합니다. SDK 선택 가이드를 참고하세요.

다음: CLOB 참고 자료 · Data API · 배관 작업 건너뛰기 - 보일러플레이트.