Skip to content

quantpylib.wrappers.polymarket

quantpylib.wrappers.polymarket is quantpylib's asynchronous Polymarket wrapper. It combines normalized gateway-style helpers with direct CLOB, Data API, Gamma API, and WebSocket methods for prediction-market workflows.

The wrapper targets Polymarket's production CLOB V2 order model on https://clob.polymarket.com, with local, optimized V2 signing and request helpers. It is designed to be performance aware and intuitive to use.

Credentials

Polymarket order-capable flows use two authentication levels:

  • Level 1 signs API-key management requests with the account private key.
  • Level 2 signs authenticated CLOB requests with the derived API key, secret, and passphrase created by init_client().

Instantiate the wrapper with the Polymarket account address, the private key used for signing, and the correct signature type:

import os

from quantpylib.wrappers.polymarket import Polymarket

poly = Polymarket(
    polymarket_key=os.getenv("POLY_KEY"),
    secret=os.getenv("POLY_SECRET"),
    sig_type=int(os.getenv("POLY_SIG", "1")),
    funder=os.getenv("POLY_FUNDER") or os.getenv("POLY_KEY"),
)

Use sig_type=1 for email or proxy-wallet accounts and sig_type=2 for browser wallet accounts. Pass funder when the funding address differs from polymarket_key; otherwise it defaults to polymarket_key.

Call await poly.init_client() before authenticated account, order, trade, allowance, or user WebSocket methods. It creates or derives CLOB API credentials and initializes the WebSocket managers. Call await poly.cleanup() when the wrapper is no longer needed to close HTTP client sessions.

async def main():
    await poly.init_client()
    try:
        print(poly.get_signer_address())
        print(poly.get_contract_config())
    finally:
        await poly.cleanup()

Gateway Helpers

Gateway-style methods normalize common account, market, order, position, and book workflows around Polymarket token IDs. A token ID is the tradable outcome asset, so the Yes and No sides of the same market use different tickers.

from pprint import pprint

TOKEN_ID = "78433024518676680431174478322854148606578065650008220678402966840627347604025"

pprint(await poly.account_balance())
pprint(await poly.contract_specifications())
pprint(await poly.orders_get())
pprint(await poly.positions_get())
pprint(await poly.l2_book_get(ticker=TOKEN_ID))

positions_get() filters zero-value positions and orders_get() converts open orders into quantpylib's standard order fields.

Orders

limit_order() creates and submits CLOB V2 orders with hash-caching and optimized signing. Positive amount values create buy orders and negative values create sell orders. Prices are rounded to the market's tick size if not provided (hence incurring network trips) and are checked against the valid tick range.

response = await poly.limit_order(
    ticker=TOKEN_ID,
    amount=10,
    price=0.01,
    tif="GTC",
)

Set submit_order=False when you need a signed order object without immediate submission:

order, tif, cloid = await poly.limit_order(
    ticker=TOKEN_ID,
    amount=10,
    price=0.01,
    submit_order=False,
)

Batch submission uses the same helper path and posts one CLOB request:

response = await poly.limit_orders([
    {"ticker": TOKEN_ID, "amount": 10, "price": 0.01, "tif": "GTC"},
])

The lower-level order methods remain available when callers already have signed orders or pre-serialized payloads:

await poly.post_order(order=order, order_type=tif)
await poly.post_orders(orders=[order], order_types=[tif])
await poly.post_order_bytes(order_payload_bytes="<serialized_order_payload>")
await poly.post_orders_bytes(orders_payload_bytes="[<serialized_order_payload>]")

Cancellation helpers include both standard IDs and pre-serialized request bodies:

await poly.cancel_order(order_id="<order_id>")
await poly.cancel_orders(order_ids=["<order_id>"])
await poly.cancel_order_bytes(cancel_payload_bytes=b'{"orderID":"<order_id>"}')
await poly.cancel_orders_bytes(cancels_payload_bytes=b'["<order_id>"]')

CLOB, Data, And Gamma Endpoints

Direct endpoint wrappers expose account allowances, API-key management, orders, trades, market metadata, books, prices, spreads, fee rates, historical prices, and Gamma market or event reads:

pprint(await poly.time())
pprint(await poly.get_collateral_allowance())
pprint(await poly.get_conditional_allowance(token_id=TOKEN_ID))
pprint(await poly.get_fee_rate(token_id=TOKEN_ID))

pprint(await poly.get_orders())
pprint(await poly.get_trades_page(limit=2))
pprint(await poly.all_clob_markets_page(limit=2))
pprint(await poly.get_book(token_id=TOKEN_ID))
pprint(await poly.get_prices_history(asset_id=TOKEN_ID, interval="1m", fidelity=60))

pprint(await poly.get_positions(limit=2))
pprint(await poly.get_bet_value())
pprint(await poly.gamma_get_markets(limit=2))

Paginator helpers such as get_orders(), get_trades(), and all_clob_markets() iterate cursor-based CLOB responses. Their *_page counterparts return a single page.

WebSockets

After init_client(), the CLOB WebSocket manager supports authenticated user streams and public market streams:

async def print_handler(message):
    pprint(message)

await poly.subscribe_user(handler=print_handler)
await poly.unsubscribe_user()

await poly.subscribe_market(handler=print_handler, asset_id=TOKEN_ID)
await poly.unsubscribe_market(asset_id=TOKEN_ID)

The real-time data stream manager is exposed as poly.realtime_manager and can subscribe to Polymarket's live crypto price feeds:

from quantpylib.wrappers.polymarket import RealTimeChannel

rtds = poly.realtime_manager

await rtds.subscribe_chainlink_prices(handler=print_handler)
await rtds.unsubscribe_chainlink_prices()

More Examples

examples/example_polymarket.py:

import os
import asyncio
import logging

from pprint import pprint
from dotenv import load_dotenv
load_dotenv()

from quantpylib.wrappers.polymarket import (
    Polymarket,
    OrderArgs,
    CreateOrderOptions,
    RealTimeChannel,
)


POLY_KEY = os.getenv("TEST_POLY_KEY") or os.getenv("POLY_KEY")
POLY_SECRET = os.getenv("TEST_POLY_SECRET") or os.getenv("POLY_SECRET")
POLY_SIG_TYPE = int(os.getenv("TEST_POLY_SIG") or os.getenv("POLY_SIG") or "1")
POLY_FUNDER = os.getenv("TEST_POLY_FUNDER") or os.getenv("POLY_FUNDER") or POLY_KEY

ORDER_ID = os.getenv("TEST_POLY_ORDER_ID") or os.getenv("POLY_ORDER_ID") or ""
TOKEN_ID = "78433024518676680431174478322854148606578065650008220678402966840627347604025"
CONDITION_ID = "0x384e2707bbb95da4bfa6f330fe7d5ccbec1c0a85e20be900cbf599987588e1a4"
MARKET_SLUG = "reya-fdv-above-200m-one-day-after-launch-645-575"
GAMMA_MARKET_ID = ""
GAMMA_EVENT_ID = ""
ORDER_PRICE = 0.01
ORDER_SIZE = 10

poly = Polymarket(
    polymarket_key=POLY_KEY,
    secret=POLY_SECRET,
    sig_type=POLY_SIG_TYPE,
    funder=POLY_FUNDER,
)


async def print_handler(msg):
    pprint(msg)


async def endpoint_examples():
    '''data api'''
    pprint(await poly.get_positions(limit=2))
    pprint(await poly.get_bet_value())
    pprint(await poly.get_portfolio_equity())

    '''clob account'''
    pprint(await poly.time())
    pprint(await poly.get_collateral_allowance())
    pprint(await poly.get_conditional_allowance(token_id=TOKEN_ID))
    pprint(await poly.get_balance_allowance(asset_type="COLLATERAL"))
    # pprint(await poly.update_balance_allowance(asset_type="COLLATERAL"))
    pprint(await poly.get_tick_size(token_id=TOKEN_ID))
    pprint(await poly.get_neg_risk(token_id=TOKEN_ID))
    pprint(await poly.get_fee_rate(token_id=TOKEN_ID))

    '''api keys'''
    # pprint(await poly.create_api_key())
    pprint(await poly.derive_api_key())
    pprint(await poly.get_api_keys())
    # pprint(await poly.delete_api_key())
    pprint(await poly.access_status())

    '''orders'''
    order, cloid = poly.builder.create_order(
        OrderArgs(
            token_id=TOKEN_ID,
            price=ORDER_PRICE,
            size=ORDER_SIZE,
            side="BUY",
        ),
        CreateOrderOptions(
            tick_size=str((await poly.get_tick_size(TOKEN_ID))["minimum_tick_size"]),
            neg_risk=bool((await poly.get_neg_risk(TOKEN_ID))["neg_risk"]),
        ),
    )
    # pprint(await poly.post_order(order=order, order_type="GTC"))
    # pprint(await poly.post_order_bytes(order_payload_bytes="<serialized_order_payload>"))
    # pprint(await poly.post_orders(orders=[order], order_types=["GTC"]))
    # pprint(await poly.post_orders_bytes(orders_payload_bytes="[<serialized_order_payload>]"))
    if ORDER_ID:
        pprint(await poly.get_order(order_id=ORDER_ID))
    pprint(await poly.get_orders())
    if ORDER_ID:
        pprint(await poly.cancel_order(order_id=ORDER_ID))
    # pprint(await poly.cancel_order_bytes(cancel_payload_bytes=b'{"orderID":"<order_id>"}'))
    # pprint(await poly.cancel_orders(order_ids=["<order_id>"]))
    # pprint(await poly.cancel_orders_bytes(cancels_payload_bytes=b'["<order_id>"]'))
    # pprint(await poly.cancel_all_orders())
    # pprint(await poly.cancel_market_orders(asset_id=TOKEN_ID))

    '''trades'''
    # pprint(await poly.get_trades())
    pprint(await poly.get_trades_page(limit=2))

    '''markets'''
    # pprint(await poly.all_clob_markets())
    pprint(await poly.all_clob_markets_page(limit=2))
    # pprint(await poly.all_sampling_markets())
    pprint(await poly.all_sampling_markets_page(limit=2))
    # pprint(await poly.all_simplified_markets())
    pprint(await poly.all_simplified_markets_page(limit=2))
    # pprint(await poly.all_sampling_simplified_markets())
    pprint(await poly.all_sampling_simplified_markets_page(limit=2))
    if CONDITION_ID:
        pprint(await poly.get_market(condition_id=CONDITION_ID))

    '''prices and books'''
    pprint(await poly.get_book(token_id=TOKEN_ID))
    pprint(await poly.get_books(token_ids=[TOKEN_ID]))
    pprint(await poly.get_price(token_id=TOKEN_ID, side="BUY"))
    pprint(await poly.get_prices(token_ids=[TOKEN_ID], sides=["BUY"]))
    pprint(await poly.get_midpoint(token_id=TOKEN_ID))
    pprint(await poly.get_midpoints(token_ids=[TOKEN_ID]))
    pprint(await poly.get_spread(token_id=TOKEN_ID))
    pprint(await poly.get_spreads(token_ids=[TOKEN_ID]))
    pprint(await poly.get_prices_history(asset_id=TOKEN_ID, interval="1m", fidelity=60))

    '''gamma'''
    pprint(await poly.gamma_get_markets(limit=2))
    if GAMMA_MARKET_ID:
        pprint(await poly.gamma_get_market(id=GAMMA_MARKET_ID))
    pprint(await poly.gamma_get_events(limit=2))
    if GAMMA_EVENT_ID:
        pprint(await poly.gamma_get_event(id=GAMMA_EVENT_ID))
    return

async def gateway_examples():
    '''utilities'''
    pprint(poly.get_polymarket_key())
    pprint(poly.get_signer_address())
    pprint(poly.get_contract_config())
    pprint(poly.get_collateral_address())
    pprint(poly.get_conditional_address())
    pprint(poly.get_exchange_address())
    pprint(poly.get_exchange_address(neg_risk=True))

    '''account'''
    pprint(await poly.account_balance())

    '''exchange'''
    pprint(await poly.contract_specifications())

    '''executor'''
    # pprint(await poly.limit_order(ticker=TOKEN_ID, amount=ORDER_SIZE, price=ORDER_PRICE))
    # pprint(await poly.market_order(ticker=TOKEN_ID, amount=ORDER_SIZE))
    pprint(await poly.l2_book_get(ticker=TOKEN_ID))

    '''orders'''
    pprint(await poly.orders_get())

    '''positions'''
    pprint(await poly.positions_get())

    '''gamma'''
    if MARKET_SLUG:
        pprint(await poly.fetch_slug_market(slug=MARKET_SLUG))

async def socket_examples():
    '''socket'''
    rtds = poly.realtime_manager

    async def stream_for(sub, unsub, duration=10):
        await sub
        await asyncio.sleep(duration)
        await unsub

    await stream_for(
        poly.subscribe_user(handler=print_handler),
        poly.unsubscribe_user(),
    )
    await stream_for(
        poly.subscribe_market(handler=print_handler, asset_id=TOKEN_ID),
        poly.unsubscribe_market(asset_id=TOKEN_ID),
    )
    await stream_for(
        rtds.subscribe_chainlink_prices(handler=print_handler),
        rtds.unsubscribe_chainlink_prices(),
    )

async def main():
    await poly.init_client()
    try:
        '''uncomment examples to run
        NOTE: that some code may trigger exchange actions such as live orders
        '''

        # await endpoint_examples()
        # await gateway_examples()
        await socket_examples()

    except Exception as exc:
        logging.exception("Error in Polymarket examples: %s", exc)
        raise
    finally:
        await poly.cleanup()


if __name__ == "__main__":
    asyncio.run(main())

API Reference

AsyncWebsocketManager

Manage Polymarket CLOB market and authenticated user WebSocket streams.

OrderBuilder

create_order(order_args, options)

Creates and signs an order

Polymarket

__init__(polymarket_key, secret, chain_id=POLYGON, sig_type=2, funder=None)

Instantiate the Polymarket wrapper.

Parameters:

Name Type Description Default
polymarket_key str

Polymarket account address used for CLOB account identity and direct portfolio reads.

required
secret str

Private key used for Level 1 signing and local CLOB V2 order signatures.

required
chain_id int

Polygon chain ID. Defaults to mainnet.

POLYGON
sig_type int

Polymarket signature type. Use 1 for email or proxy wallet accounts and 2 for browser wallet accounts.

2
funder str | None

Funding address for orders when it differs from polymarket_key.

None

access_status() async

Get the access status (if user has cert_required=True, one is required to provide proof of residence).

account_balance(**kwargs) async

Get the account balance. Includes total equity, cash, and bets.

all_clob_markets(**kwargs) async

Get all clob markets with iterated pagination.

all_clob_markets_page(**kwargs) async

Get all clob markets without iterated pagination.

all_sampling_markets(**kwargs) async

Get all sampling markets with iterated pagination.

all_sampling_markets_page(**kwargs) async

Get all sampling markets without iterated pagination.

all_sampling_simplified_markets(**kwargs) async

Get all sampling simplified markets with iterated pagination.

all_sampling_simplified_markets_page(**kwargs) async

Get all sampling simplified markets without iterated pagination.

all_simplified_markets(**kwargs) async

Get all simplified markets with iterated pagination.

all_simplified_markets_page(**kwargs) async

Get all simplified markets without iterated pagination.

cancel_all_orders(**kwargs) async

Cancel all orders.

cancel_market_orders(market=None, asset_id=None, **kwargs) async

Cancel all orders for a market.

Parameters:

Name Type Description Default
market str

The market ID. Defaults to None.

None
asset_id str

The asset ID. Defaults to None.

None

cancel_order(order_id, **kwargs) async

Cancel an order by ID.

cancel_order_bytes(cancel_payload_bytes, **kwargs) async

Cancel an order using a pre-serialized payload.

Parameters:

Name Type Description Default
cancel_payload_bytes bytes | str

UTF-8 bytes or string containing the exact JSON cancel payload to sign and send.

required

Returns:

Type Description
dict

CLOB cancellation response.

cancel_orders(order_ids, **kwargs) async

Cancel multiple orders by IDs.

cancel_orders_bytes(cancels_payload_bytes, **kwargs) async

Cancel multiple orders using a pre-serialized payload.

Parameters:

Name Type Description Default
cancels_payload_bytes bytes | str

UTF-8 bytes or string containing the exact JSON batch-cancel payload to sign and send.

required

Returns:

Type Description
dict

CLOB batch cancellation response.

cleanup() async

Close open HTTP client sessions.

contract_specifications(**kwargs) async

Get the contract specifications of all markets (expired and trading).

create_api_key(nonce=None) async

Create an API key.

delete_api_key(nonce=None) async

Delete the API key.

derive_api_key(nonce=None) async

Derive the API key.

fetch_slug_market(slug) async

Uses the Gamma API to fetch the market by slug.

gamma_get_event(id, **kwargs) async

Get an event by ID from the Gamma API.

Parameters:

Name Type Description Default
id str

The event ID.

required
kwargs dict

The query parameters.

{}

gamma_get_events(**kwargs) async

Get all events from the Gamma API.

Parameters:

Name Type Description Default
kwargs dict

The query parameters.

{}

gamma_get_market(id, **kwargs) async

Get a market by ID from the Gamma API.

Parameters:

Name Type Description Default
id str

The market ID.

required
kwargs dict

The query parameters.

{}

gamma_get_markets(**kwargs) async

Get all markets from the Gamma API.

Parameters:

Name Type Description Default
kwargs dict

The query parameters.

{}

get_api_keys(nonce=None) async

Get all API keys.

get_balance_allowance(asset_type, token_id=None, signature_type=-1, **kwargs) async

The correct token allowances must be set before orders can be placed. The following mainnet (Polygon) allowances should be set by the funding (maker) address. See: https://github.com/Polymarket/py-clob-client?tab=readme-ov-file#allowances

get_bet_value(**kwargs) async

Get the value of the user's bets (officially undocumented endpoint).

get_book(token_id, **kwargs) async

Get the book for a token.

Parameters:

Name Type Description Default
token_id str

The token ID.

required

get_books(token_ids=[], **kwargs) async

Get the books for multiple tokens.

Parameters:

Name Type Description Default
token_ids list

The token IDs. Defaults to [].

[]

get_collateral_allowance(signature_type=-1) async

Get the collateral allowance amount.

get_conditional_allowance(token_id, signature_type=-1) async

Get the conditional allowance amount.

get_fee_rate(token_id, **kwargs) async

Get the fee rate for a token.

get_market(condition_id, **kwargs) async

Get a market by condition ID.

Parameters:

Name Type Description Default
condition_id str

The condition ID.

required

get_midpoint(token_id, **kwargs) async

Get the midpoint for a token.

Parameters:

Name Type Description Default
token_id str

The token ID.

required

get_midpoints(token_ids=[], **kwargs) async

Get the midpoints for multiple tokens.

Parameters:

Name Type Description Default
token_ids list

The token IDs. Defaults to [].

[]

get_neg_risk(token_id, **kwargs) async

Get the negative risk of the token.

get_order(order_id, **kwargs) async

Get an order by ID.

get_orders(**kwargs) async

Get all orders with iterated pagination.

get_orders_page(**kwargs) async

Get all orders without iterated pagination.

get_positions(limit=100, **kwargs) async

Get positions of the user (officially undocumented endpoint).

get_price(token_id, side, **kwargs) async

Get the price for a token.

Parameters:

Name Type Description Default
token_id str

The token ID.

required
side str

The side BUY or SELL.

required

get_prices(token_ids=[], sides=[], **kwargs) async

Get the prices for multiple tokens.

Parameters:

Name Type Description Default
token_ids list

The token IDs. Defaults to [].

[]
sides list

The sides BUY or SELL. Defaults to [].

[]

get_prices_history(asset_id, **kwargs) async

Get price history for a market asset.

get_spread(token_id, **kwargs) async

Get the spread for a token.

Parameters:

Name Type Description Default
token_id str

The token ID.

required

get_spreads(token_ids=[], **kwargs) async

Get the spreads for multiple tokens.

Parameters:

Name Type Description Default
token_ids list

The token IDs. Defaults to [].

[]

get_tick_size(token_id, **kwargs) async

Get the tick size of the token.

get_trades(**kwargs) async

Get all trades with iterated pagination.

get_trades_page(**kwargs) async

Get all trades without iterated pagination.

init_client() async

Initialize authenticated CLOB credentials and WebSocket managers.

This method creates or derives the Level 2 API key, secret, and passphrase used by authenticated CLOB requests. Call it before account, allowance, order, trade, or user WebSocket methods.

l2_book_get(ticker, as_dict=True, **kwargs) async

Retrieve L2 snapshot for a given coin.

Parameters:

Name Type Description Default
ticker str

The Polymarket token ID for the yes/no outcome asset.

required
as_dict bool

If True, return the standardized dictionary representation. If False, return the LOB object. Defaults to True.

True
**kwargs dict

Exchange wrapper specific keyword arguments.

{}

Returns:

Type Description
dict | LOB

A dictionary containing the L2 snapshot information, or the underlying LOB object when as_dict is False.

limit_helper(ticker, amount, price, round_price=True, tick_size=None, neg_risk=None, expiration=0, **kwargs) async

Build a signed CLOB V2 limit order without submitting it.

Parameters:

Name Type Description Default
ticker str

Polymarket token ID for the outcome asset.

required
amount float

Signed order size. Positive values buy and negative values sell the outcome token.

required
price float

Limit price.

required
round_price bool

Whether to round price to the market tick size.

True
tick_size str | None

Optional pre-fetched tick size. When omitted, the wrapper requests it from the CLOB.

None
neg_risk bool | None

Optional pre-fetched negative-risk flag. When omitted, the wrapper requests it from the CLOB.

None
expiration int

GTD expiration timestamp used by the CLOB order model.

0

Returns:

Type Description
tuple

Signed order object and generated client order ID.

limit_order(ticker, amount, price, tif='GTC', round_price=True, tick_size=None, neg_risk=None, submit_order=True, post_only=False, defer_exec=False, expiration=0, **kwargs) async

Submit a limit order.

Parameters:

Name Type Description Default
ticker str

The Polymarket token ID for the yes/no outcome asset.

required
amount float or Decimal

The signed quantity of contracts to long or short.

required
price float

The price at which to execute the order.

required
tif str

The time in force for the order. Defaults to "GTC". Allowed values are "GTC", "FOK", and "GTD".

'GTC'
round_price bool

Whether to round the price to a valid order specification. Defaults to True.

True
tick_size str

Pre-fetched Polymarket tick size. Defaults to None.

None
neg_risk bool

Pre-fetched Polymarket negative-risk flag. Defaults to None.

None
submit_order bool

If True, sign and POST the order. If False, return the signed (order, tif, cloid) tuple for later submission. Defaults to True.

True
post_only bool

Whether the order should only add liquidity. Defaults to False.

False
defer_exec bool

Whether the CLOB should defer execution. Defaults to False.

False
expiration int

GTD expiration timestamp used by the CLOB order model. Defaults to 0.

0
**kwargs dict

Additional keyword arguments for order customization.

{}

Returns:

Type Description
Any

The result of the order placement, the deferred signed order tuple, or None for zero-sized orders.

limit_orders(limit_order_list, **kwargs) async

Build and submit multiple limit orders in one CLOB request.

Parameters:

Name Type Description Default
limit_order_list list

Sequence of keyword dictionaries accepted by limit_order().

required

Returns:

Type Description
dict | list

CLOB batch submission response, or an empty list when every requested order has zero size.

market_order(ticker, amount, tif='GTC', **kwargs) async

Submit a market order.

Parameters:

Name Type Description Default
ticker str

The Polymarket token ID for the yes/no outcome asset.

required
amount float or Decimal

The signed quantity of contracts to long or short.

required
tif str

The time in force for the backing limit order. Defaults to "GTC".

'GTC'
**kwargs dict

Exchange wrapper specific keyword arguments.

{}

Returns:

Type Description
Any

The result of the order placement.

orders_get(**kwargs) async

Get all open order details.

Parameters:

Name Type Description Default
**kwargs dict

Additional keyword arguments specific to the exchange wrapper.

{}

Returns:

Type Description
dict

A dictionary containing details of all open orders. Each key is the order ID, with value dict:

  • markets.TICKER: The Polymarket token ID.
  • markets.ORDER_ID: The unique identifier of the order.
  • markets.LIMIT_PRICE: The limit price of the order.
  • markets.ORDER_AMOUNT: The original size of the order.
  • markets.ORDER_FILLED_SIZE: The size of the order that has been filled.
  • markets.TIME_IN_FORCE: The time in force for the order.
  • markets.TIMESTAMP: The timestamp when the order was created.

positions_get(**kwargs) async

Get all open position details.

Parameters:

Name Type Description Default
**kwargs dict

Additional keyword arguments specific to the exchange wrapper.

{}

Returns:

Type Description
dict

A dictionary containing details of the open positions.

post_order(order, order_type='GTC', post_only=False, defer_exec=False, **kwargs) async

Submit one signed CLOB V2 order.

Parameters:

Name Type Description Default
order SignedOrderV2

Signed CLOB order object created by the local order builder.

required
order_type str

CLOB time-in-force value.

'GTC'
post_only bool

Whether the order should only add liquidity.

False
defer_exec bool

Whether the CLOB should defer execution.

False

Returns:

Type Description
dict

CLOB order submission response.

post_order_bytes(order_payload_bytes, **kwargs) async

Submit one pre-serialized CLOB order payload.

Parameters:

Name Type Description Default
order_payload_bytes bytes | str

UTF-8 bytes or string containing the exact JSON payload to sign and send.

required

Returns:

Type Description
dict

CLOB order submission response.

post_orders(orders, order_types, post_onlys=None, defer_execs=None, **kwargs) async

Submit multiple signed CLOB V2 orders in one request.

Parameters:

Name Type Description Default
orders list

Signed CLOB order objects.

required
order_types list

CLOB time-in-force value for each order.

required
post_onlys list | None

Optional post-only flag for each order.

None
defer_execs list | None

Optional defer-execution flag for each order.

None

Returns:

Type Description
dict

CLOB batch order submission response.

post_orders_bytes(orders_payload_bytes, **kwargs) async

Submit a pre-serialized CLOB batch order payload.

Parameters:

Name Type Description Default
orders_payload_bytes bytes | str

UTF-8 bytes or string containing the exact JSON payload to sign and send.

required

Returns:

Type Description
dict

CLOB batch order submission response.

subscribe_market(handler, asset_id) async

Subscribe to public CLOB market events for one outcome asset.

Parameters:

Name Type Description Default
handler Callable

Async callback that receives raw CLOB WebSocket messages.

required
asset_id str

Polymarket token ID for the outcome asset.

required

subscribe_user(handler, condition_ids=None) async

Subscribe to authenticated CLOB user events.

Parameters:

Name Type Description Default
handler Callable

Async callback that receives raw CLOB WebSocket messages.

required
condition_ids list | None

Optional market condition IDs to filter user events. Defaults to all authenticated user events.

None

time() async

Get the exchange server time.

unsubscribe_market(asset_id) async

Unsubscribe from public CLOB market events for one outcome asset.

Parameters:

Name Type Description Default
asset_id str

Polymarket token ID used for the original subscription.

required

unsubscribe_user(condition_ids=None) async

Unsubscribe from authenticated CLOB user events.

Parameters:

Name Type Description Default
condition_ids list | None

Optional market condition IDs used for the original subscription. Defaults to the unfiltered user subscription.

None

update_balance_allowance(asset_type, token_id=None, signature_type=-1, **kwargs) async

Update the balance allowance amount. If asset type is CONDITIONAL, the token ID is required.

RealTimeChannel

Polymarket real-time data stream channel names.

RealTimeWebsocketManager

Manage Polymarket real-time data stream price subscriptions.

subscribe_binance_prices(handler, tickers) async

Subscribe to RTDS Binance-indexed crypto price updates.

Parameters:

Name Type Description Default
handler Callable

Async callback that receives raw RTDS WebSocket messages.

required
tickers Iterable[str]

Iterable of symbols such as BTCUSDT.

required

Subscribe to RTDS Chainlink crypto price updates.

Parameters:

Name Type Description Default
handler Callable

Async callback that receives raw RTDS WebSocket messages.

required

subscribe_prices(handler, channel=RealTimeChannel.BINANCE, type='', filters='') async

Subscribe to a Polymarket real-time data stream price channel.

Parameters:

Name Type Description Default
handler Callable

Async callback that receives raw RTDS WebSocket messages.

required
channel str

RTDS channel name from RealTimeChannel.

BINANCE
type str

RTDS event type filter.

''
filters str | dict

Symbol filter string or raw RTDS filter object.

''

unsubscribe_binance_prices(tickers) async

Unsubscribe from RTDS Binance-indexed crypto price updates.

Parameters:

Name Type Description Default
tickers Iterable[str]

Iterable of symbols used for the original subscription.

required

Unsubscribe from RTDS Chainlink crypto price updates.

unsubscribe_prices(channel=RealTimeChannel.BINANCE, type='', filters='') async

Unsubscribe from a Polymarket real-time data stream price channel.

Parameters:

Name Type Description Default
channel str

RTDS channel name from RealTimeChannel.

BINANCE
type str

RTDS event type filter used for the original subscription.

''
filters str | dict

Symbol filter string or raw RTDS filter object used for the original subscription.

''

build_hmac_signature(secret, timestamp, method, endpoint, body=None)

Creates an HMAC signature by signing a payload with the secret

create_level_1_headers(signer, nonce=None, **kwargs)

Creates Level 1 Poly headers for a request

create_level_2_headers(signer, method, endpoint, api_key, api_secret, api_passphrase, json=None, data=None, **kwargs)

Creates Level 2 Poly headers for a request

get_contract_config(chainID, neg_risk=False)

Get the contract configuration for the chain