Skip to main content
Use the Polymarket integration to build agents that buy and sell shares in prediction markets. Common use cases include event-driven trading, portfolio hedging, and automated redemption of settled positions.

Market Order

Execute a buy or sell market order.
def market_order(request: PolymarketMarketOrderRequest | PolymarketMarketOrderRequestInput) -> PolymarketMarketOrderResponse
Request Parameters:
  • tokenId (string): Market token ID for the position
  • size (number): Order size (meaning differs by side)
  • side (string): “BUY” or “SELL”
  • idempotencyKey (string, optional): Durable retry key for auto-mode market orders. SDKs generate one automatically; provide a stable key only when retrying the same logical order after a process restart.
  • expiresAt (string | null, optional): ISO 8601 timestamp. In manual mode, the suggestion expires at this time. If omitted, no time-based expiry is set (suggestions are auto-cleared at each run start).
Size Parameter:
  • BUY: size is the USD amount to spend (e.g., 10 = $10 worth of shares)
  • SELL: size is the number of shares to sell (e.g., 10 = 10 shares)
Auto-mode market orders are idempotent by idempotencyKey within the current agent run. Duplicate active or already-submitted attempts are rejected; only failures before any external side effect can retry under the same key. Response:
  • success (boolean): Whether the operation succeeded
  • data.orderInfo (object): Order information (on success)
    • orderId (string): Unique order identifier
    • side (string): “BUY” or “SELL”
    • size (string): Order size
    • priceUsd (string): Price per share in USD
    • totalPriceUsd (string): Total order value in USD
    • txHashes (string[]): Transaction hashes
  • error (string | null): Error message (on failure)
Example:
# BUY order - size is USD amount to spend
# tokenId comes from Polymarket's API for the specific outcome you want to trade
token_id = "71321045679252212594626385532706912750332728571942532289631379312455583992563"

buy_result = agent.platforms.polymarket.market_order({
    "tokenId": token_id,
    "size": 10,  # Spend $10 to buy shares
    "side": "BUY"
})

if buy_result.success and buy_result.data:
    agent.log(f"Order ID: {buy_result.data.order_info.order_id}")
    agent.log(f"Total Price: ${buy_result.data.order_info.total_price_usd}")
    agent.log(f"Price per share: ${buy_result.data.order_info.price_usd}")

# SELL order - size is number of shares to sell
sell_result = agent.platforms.polymarket.market_order({
    "tokenId": token_id,
    "size": 5,  # Sell 5 shares
    "side": "SELL"
})

if sell_result.success and sell_result.data:
    agent.log(f"Sold {sell_result.data.order_info.size} shares")
    agent.log(f"Received: ${sell_result.data.order_info.total_price_usd}")

Redeem Positions

Redeem settled positions and claim winnings. Pass the token IDs of the positions to redeem — fetch your positions first and filter for isRedeemable. Agents only redeem positions their own session holds; there is no “redeem everything in the wallet” mode.
def redeem_positions(request: PolymarketRedeemPositionsRequest | PolymarketRedeemPositionsRequestInput) -> PolymarketRedeemPositionsResponse
Request Parameters (required):
  • tokenIds (string[], required, non-empty): Token IDs of the positions to redeem. Requesting a token the session doesn’t hold fails with a 404.
  • idempotencyKey (string, optional): Durable retry key for auto-mode redeem attempts. SDKs generate one per redeemPositions() / redeem_positions() call when omitted.
Use an explicit idempotencyKey only when retrying the same logical redeem after a process restart. Active attempts and attempts that already reached an onchain side effect return a conflict for the same key; only failures before any broadcast can retry under the same key. Response:
  • success (boolean): Whether the operation succeeded
  • data (array): Array of redemption results
    • success (boolean): Whether this redemption succeeded
    • position (object | null): Position details (on success)
      • question (string): Market question text
      • outcome (string): Outcome name (e.g., “Yes”, “No”)
      • valueUsd (string): Position value in USD
      • pnlUsd (string): Profit/loss in USD
      • pnlPercent (string): Profit/loss percentage
      • isRedeemable (boolean): Whether position can be redeemed
      • contractAddress (string): Token contract address
      • tokenId (string | null): Token ID
      • decimals (number): Token decimals
      • conditionId (string): Market condition ID
      • formattedShares (string): Human-readable share count
      • shares (string): Raw share count
      • averagePriceUsd (string): Average entry price
      • initialValue (string): Original position value
      • pnlRealizedUsd (string): Realized PnL in USD
      • pnlRealizedPercent (string): Realized PnL percentage
      • isNegativeRisk (boolean): Whether this is a negative risk market
      • imageUrl (string): Market image URL
      • endDate (string): Market end date
    • transactionHash (string | null): Transaction hash. null with success: false means the position was skipped (not settled yet) and no transaction was broadcast.
    • skippedReason (string, optional): Why the position was skipped without broadcasting (e.g. not settled yet). Present only when success is false.
  • error (string | null): Error message (on failure)
In manual mode the redeem is captured as a suggestion for the user to approve; data is then a suggestion envelope ({ suggested: true, suggestionId }) instead of the redemption array. See Manual vs Auto Mode. Example:
# Redeem this agent's settled positions
portfolio = agent.platforms.polymarket.positions()
redeemable = [
    p.token_id
    for p in (portfolio.data.positions if portfolio.success and portfolio.data else [])
    if p.is_redeemable and p.token_id
]

if redeemable:
    redemption = agent.platforms.polymarket.redeem_positions({"tokenIds": redeemable})

    if redemption.success and redemption.data:
        successful = [r for r in redemption.data if r.success]
        agent.log(f"Redeemed {len(successful)} positions")

        for tx in redemption.data:
            if tx.success and tx.position:
                agent.log(f"Redeemed: {tx.position.question} ({tx.position.outcome})")
                agent.log(f"Value: ${tx.position.value_usd}")
                agent.log(f"PnL: ${tx.position.pnl_usd} ({tx.position.pnl_percent}%)")
                agent.log(f"Tx: {tx.transaction_hash}")

Get Positions

Get the session’s live Polymarket positions, enriched with market metadata (question, outcome, price, value, redeemability, PnL). Scoped to the outcome tokens this session holds. Use this for fresh state after trading within a run — agent.portfolio.positions carries the same enrichment but as a start-of-run snapshot, so it won’t reflect orders placed during the current run.
def positions() -> PolymarketPositionsResponse
Response:
  • success (boolean): Whether the operation succeeded
  • data.totalValue (number): Total USD value of the session’s Polymarket positions
  • data.positions (array): Enriched positions — each with tokenId, question, outcome, priceUsd, valueUsd, shares, isRedeemable, pnlUsd, pnlPercent, endDate, …
  • error (string): Error message (only present on failure)
result = agent.platforms.polymarket.positions()
if result.success and result.data:
    for pos in result.data.positions:
        agent.log(f"{pos.question} [{pos.outcome}]: ${pos.value_usd} (PnL ${pos.pnl_usd})")
        if pos.is_redeemable:
            agent.log(f"  redeemable — tokenId {pos.token_id}")

Common Errors

Errors are returned from Polymarket’s API in the error field. Common errors include:
ErrorCauseSolution
”Insufficient balance”Not enough pUSD for BUY orderCheck agent.portfolio.balances for pUSD balance
”No orderbook exists for the requested token id”Invalid tokenId or market doesn’t existVerify tokenId from Polymarket API
Note: Additional error messages may be returned by Polymarket’s API. Check the error field in the response for specific details.

Getting Token IDs

The tokenId identifies a specific outcome (e.g., “Yes” or “No”) in a Polymarket market. You can find token IDs through:
  • Polymarket’s CLOB API: GET https://clob.polymarket.com/markets returns all markets with their tokens array, each containing a token_id and outcome.
  • From your holdings: If you already hold shares, agent.portfolio.positions includes Polymarket positions with token IDs in position.polymarketMetadata.tokenId.

Notes

  • Polymarket’s API accepts different decimal precision for buys and sells. This can result in dust positions if selling a position before expiry. Clean up dust with redeemPositions({ tokenIds }) after market expiry.
  • Negative risk markets: Some markets use an inverted pricing model. The SDK handles this transparently, but be aware that position values may display differently.
  • Open positions are available via agent.portfolio.positions (pUSD cash stays in agent.portfolio.balances).
  • Polymarket positions always include enriched metadata (question, outcome, PNL) on position.polymarketMetadata.
  • SDKs generate idempotencyKey automatically for marketOrder and redeemPositions; pass a stable key only when you need to resume the same logical action after a process restart.

See Also