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 | dict) -> PolymarketMarketOrderResponse
Request Parameters:
  • tokenId (string): Market token ID for the position
  • size (number): Order size (meaning differs by side)
  • side (string): “BUY” or “SELL”
  • 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).
  • waitForConfirmation (boolean, optional): If true (default), the SDK polls for transaction receipts after the order executes and returns success: false if any transaction reverted onchain. Set to false to skip receipt polling.
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)
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.orderInfo.orderId}")
    agent.log(f"Total Price: ${buy_result.data.orderInfo.totalPriceUsd}")
    agent.log(f"Price per share: ${buy_result.data.orderInfo.priceUsd}")

# 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.orderInfo.size} shares")
    agent.log(f"Received: ${sell_result.data.orderInfo.totalPriceUsd}")

Redeem Positions

Redeem settled positions and claim winnings.
def redeem_positions(request: PolymarketRedeemPositionsRequest | None = None) -> PolymarketRedeemPositionsResponse
Request Parameters (optional):
  • tokenIds (string[], optional): Specific token IDs to redeem. Omit or pass empty array to redeem all redeemable positions.
  • waitForConfirmation (boolean, optional): If true (default), the SDK polls for transaction receipts after redemption and returns success: false if any transaction reverted onchain. Set to false to skip receipt polling.
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 (on success)
  • error (string | null): Error message (on failure)
Example:
# Redeem all redeemable positions
redemption = agent.platforms.polymarket.redeem_positions()

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.valueUsd}")
            agent.log(f"PnL: ${tx.position.pnlUsd} ({tx.position.pnlPercent}%)")
            agent.log(f"Tx: {tx.transactionHash}")

# Redeem specific positions by tokenId
specific_result = agent.platforms.polymarket.redeem_positions({
    "tokenIds": [
        "71321045679252212594626385532706912750332728571942532289631379312455583992563",
        "52114319501245915516055106046884209969926127482827954674443846427813813222426"
    ]
})

Common Errors

Errors are returned from Polymarket’s API in the error field. Common errors include:
ErrorCauseSolution
”Insufficient balance”Not enough USDC for BUY orderCheck currentPositions for USDC 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 positions: If you already hold shares, getCurrentPositions() returns Polymarket positions with token IDs in the position data.

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() 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.
  • Position data is available via agent.currentPositions and agent.getCurrentPositions().
  • Polymarket positions include enriched metadata (question, outcome, PNL) when retrieved via getCurrentPositions().

See Also