Skip to content

quantpylib.wrappers.polymarket

quantpylib.wrappers.polymarket module is our official Polymarket wrapper SDK implementing the endpoints for contract betting. The library supports a fully asynchronous endpoint for efficiency and lightweight concurrency.

We will demonstrate usage of the library. On top of the endpoints exposed by the exchange, we have added a variety of utility functions and officially undocumented endpoints!

Examples

Let's start with the imports and code initiation:

import os 
import asyncio 

from pprint import pprint 
from datetime import datetime 
from dotenv import load_dotenv
load_dotenv()

from quantpylib.wrappers.polymarket import Polymarket

async def main():
    pass #<< code goes here

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

By far the biggest complaint with their SDK and their documentation is how ridiculously difficult it is to get the correct configurations to submit API orders. Here is the run down.

You deposit money into Polymarket. This is in USDC. You need to permit USDC.E allowance - you can do this in the UI after you sending the funds. This is pretty clear from their user interface, and actually does not require automation.

When you instantiate the SDK - you need to know which type of account you are using. This is actually detailed in their documentation with 3 kinds of instantiation - using the EOA address, Email login or Browser Wallet login.

There are multiple keys involved. If you used a Browser wallet, there will be the Polygon address (KEY1) of that wallet. Then there is the secret key (KEY2) that is paired with the Polygon address. Then there is also the public and private key pair associated with the Polymarket account. This can be exported from their web trading platform under Deposit > Desposit Address (public, KEY3) > Balance.More > Export Private Key (private, KEY4).

With the email wallet login, your environment variables would be

polymarket_key = KEY1
secret = KEY4
sig_type = 1
and with the browser wallet login, your environment variables would be
polymarket_key = KEY1
secret = KEY2
sig_type = 2
I hope that is clear and saved you some time scouring through their 'Github issues' or 'Discord/dev' channel.

With that in mind, let's write some code! The polymarket SDK wrapper is only partially gateway-compatible, obviously due to the unique nature of betting markets as opposed to perpetual or spot markets.

We can start with this (self-explanatory):

async def main():
    '''using the SDK'''
    poly = Polymarket(
        polymarket_key=os.getenv("POLY_KEY"),
        secret=os.getenv("POLY_SECRET"),
        sig_type=1
    )
    await poly.init_client()

    print(poly.get_polymarket_key())
    print(poly.get_signer_address())
    print(poly.get_contract_config())
    print(poly.get_conditional_address())
    print(poly.get_exchange_address())

You can get your account balances like this:

'''GATEWAY ENDPOINTS'''
pprint(await poly.account_balance())
which gives output like this:
{'bets': Decimal('0.95'),
 'cash': Decimal('504.192361'),
 'equity_total': 505.142361}
This is actually not an endpoint available in their API documentation or SDK, but are the figures shown in the top bar on your trader platform!

We can ask for market summaries;

pprint(await poly.contract_specifications())
and this gets us (we have automatically iterated the cursors to poll full results):
...
{'accepting_order_timestamp': '2024-12-22T07:08:56Z',
           'accepting_orders': True,
           'active': True,
           'archived': False,
           'closed': False,
           'condition_id': '0x9915bea232fa12b20058f9cea1187ea51366352bf833393676cd0db557a58249',
           'description': 'In the upcoming NHL game, scheduled for blah blah blah',
           'enable_order_book': True,
           'end_date_iso': '2025-01-05T00:00:00Z',
           'fpmm': '0x32a8d457aF8d063111303178689bdb91DAab0581',
           'game_start_time': '2024-12-29T00:00:00Z',
           'icon': 'https://polymarket-upload.s3.us-east-2.amazonaws.com/nhl.png',
           'image': 'https://polymarket-upload.s3.us-east-2.amazonaws.com/nhl.png',
           'is_50_50_outcome': False,
           'maker_base_fee': 0,
           'market_slug': 'nhl-wsh-tor-2024-12-28',
           'minimum_order_size': 5,
           'minimum_tick_size': 0.01,
           'neg_risk': False,
           'neg_risk_market_id': '',
           'neg_risk_request_id': '',
           'notifications_enabled': False,
           'question': 'Capitals vs. Maple Leafs',
           'question_id': '0xfefa98bc82182b8f385298de3842ea8f8c2beaaed87ef1812eeb787b34f7ab1c',
           'rewards': {'max_spread': 0, 'min_size': 0, 'rates': None},
           'seconds_delay': 3,
           'tags': ['Sports', 'NHL', 'Games'],
           'taker_base_fee': 0,
           'tokens': [{'outcome': 'Capitals',
                       'price': 0.5,
                       'token_id': '60989902840126768738269456361150551078629202162302557022265426129538140181471',
                       'winner': False},
                      {'outcome': 'Maple Leafs',
                       'price': 0.5,
                       'token_id': '29299903966152818260760859271342991417079619740850848288273676438278713549119',
                       'winner': False}]}],
 'limit': 22551,
 'next_cursor': 'LTE='
as well as the current open orders and positions:
pprint(await poly.orders_get())
pprint(await poly.positions_get())
which gives
{'abcd': {'amount': Decimal('10'),
        'filled_sz': Decimal('0'),
        'market': '0x87d67272f0ce1bb0d80ba12a1ab79287b2a235a5f361f5bcbc06ea0ce34e61c5',
        'oid': 'abcd',
        'outcome': 'Yes',
        'price': Decimal('0.77'),
        'ticker': '25788984364015292223605977307142748201985724991469784186655292374059222006895',
        'tif': 'GTC',
        'timestamp': 1734885235}}
 ...
for the resting orders and
{'efg': {'amount': Decimal('100'),
        'entry': Decimal('0.012'),
        'event_slug': 'us-government-shutdown-before-2025',
        'market': '0x87d67272f0ce1bb0d80ba12a1ab79287b2a235a5f361f5bcbc06ea0ce34e61c5',
        'opposite': '25788984364015292223605977307142748201985724991469784186655292374059222006895',
        'outcome': 'No',
        'slug': 'us-government-shutdown-before-2025',
        'ticker': 'efg',
        'value': Decimal('0.8999999999999999')}}
for the positions. We have made it super easy to submit orders, almost as if it is a normal spot market - just put in the correct ticker (they are different for yes or no)
print(
    await poly.limit_order(
        ticker="19045189272319329424023217822141741659150265216200539353252147725932663608488",
        amount=10,
        price=0.1,
    )
)
as well as market (taker) orders:
print(
    await poly.market_order(
        ticker="19045189272319329424023217822141741659150265216200539353252147725932663608488",
        amount=10,
    )
)
and order book snapshots:
print(await poly.l2_book_get(ticker="19045189272319329424023217822141741659150265216200539353252147725932663608488",))

That's it for the gateway endpoints - of course we have all of the exchange API documented endpoints directly available too:

pprint(await poly.time())
pprint(await poly.get_collateral_allowance())
pprint(await poly.get_tick_size(token_id="19045189272319329424023217822141741659150265216200539353252147725932663608488"))
pprint(await poly.create_api_key())
pprint(await poly.derive_api_key())
pprint(await poly.get_api_keys())
pprint(await poly.access_status())

await poly.post_order(order=None)
pprint(await poly.get_order(order_id="123")) 
pprint(await poly.get_orders())
pprint(await poly.cancel_order(order_id="123"))
pprint(await poly.cancel_orders(order_ids=[]))
pprint(await poly.cancel_all_orders())
pprint(await poly.cancel_market_orders(market="123"))
and much more! Happy trading/speculating/arbitraging.

OrderBuilder

create_order(order_args, options)

Creates and signs an order

Polymarket

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

Instantiates the Polymarket wrapper class.

Parameters:

Name Type Description Default
polymarket_key str

The Polymarket account key. (Top RHS, copy address)

required
secret str

The Polygon secret key (browser wallet) or Polymarket secret (email wallet - Deposit > Expand ... > Export private key).

required
chain_id int

The Polygon chain ID. Defaults to 137.

POLYGON
sig_type int

The signature type. Defaults to 2. 1 if email wallet, 2 if Browser wallet.

2
funder str

The funder address. Defaults to 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_orders(order_ids, **kwargs) async

Cancel multiple orders by IDs.

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_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_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 the Polymarket client.

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

Get the level 2 book.

Parameters:

Name Type Description Default
ticker str

The token ID for yes or no of relevant market.

required
as_dict bool

Whether to return the book as a dictionary. Defaults to True.

True

limit_order(ticker, amount, price, tif='GTC', round_price=True, tick_size=None, **kwargs) async

Place a limit order.

Parameters:

Name Type Description Default
ticker str

The token ID for yes or no of relevant market. Also known as token_id or asset_id.

required
amount float

The signed amount of the token.

required
price float

The price of the limit order.

required
tif str

The time in force. Defaults to 'GTC'.

'GTC'
round_price bool

Whether to round the price. Defaults to True.

True
tick_size str

The tick size. Defaults to None.

None

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

Place a market order.

Parameters:

Name Type Description Default
ticker str

The token ID for yes or no of relevant market.

required
amount float

The signed amount of the token.

required
tif str

The time in force. Defaults to 'GTC'.

'GTC'

orders_get(**kwargs) async

Get all open orders.

positions_get(**kwargs) async

Get all open positions.

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

Post an order.

time() async

Get the exchange server time.

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.

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, **kwargs)

Creates Level 2 Poly headers for a request

get_contract_config(chainID, neg_risk=False)

Get the contract configuration for the chain