=============== LIBRARY RULES =============== From library maintainers: - PolySimulator is a prediction market trading simulator, NOT a polynomial math library. - All API endpoints are under /v1/ prefix and require X-API-Key header authentication. - Price and balance values are always strings to avoid floating-point precision loss. - Virtual trading uses real Polymarket CLOB order book data with simulated balances. - To switch from paper to live trading, change only the API credentials — no code changes. ### Python Example Setup Source: https://github.com/bavariance/polysimulator-docs/blob/main/account/positions.mdx Initializes the Python requests client with base URL and API key from environment variables. ```python import requests, os from decimal import Decimal BASE_URL = os.environ["POLYSIM_BASE_URL"] headers = {"X-API-Key": os.environ["POLYSIM_API_KEY"]} ``` -------------------------------- ### Place Order using Polymarket SDK (Live Mode) Source: https://github.com/bavariance/polysimulator-docs/blob/main/deployment/live-migration.mdx Example of placing an order using the Polymarket SDK for live trading. This demonstrates the client setup with API credentials and the SDK's order submission method. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds # Client setup + submission method changes; order field semantics stay close: api_creds = ApiCreds( api_key=os.getenv("POLY_API_KEY"), api_secret=os.getenv("POLY_API_SECRET"), api_passphrase=os.getenv("POLY_PASSPHRASE"), ) client = ClobClient( "https://clob.polymarket.com", chain_id=137, key=os.getenv("PRIVATE_KEY"), creds=api_creds, ) # Same trading intent, submitted via Polymarket SDK order flow: from py_clob_client.clob_types import OrderArgs, OrderType from py_clob_client.order_builder.constants import BUY signed_order = client.create_order( OrderArgs( token_id="71321045679252...", side=BUY, price=0.65, size=10, ) ) result = client.post_order(signed_order, OrderType.GTC) print(result) ``` -------------------------------- ### Install py-clob-client SDK Source: https://github.com/bavariance/polysimulator-docs/blob/main/llms.txt Installs the necessary Python package for interacting with the Polymarket CLOB. ```bash pip install py-clob-client ``` -------------------------------- ### Get Account Balance with API Key Source: https://github.com/bavariance/polysimulator-docs/blob/main/api-reference/overview.mdx Example of how to fetch account balance using a curl command with the required X-API-Key header. ```bash curl https://api.polysimulator.com/v1/account/balance \ -H "X-API-Key: ps_live-..." ``` -------------------------------- ### Install Dependencies and Run Trading Bot Source: https://github.com/bavariance/polysimulator-docs/blob/main/bots/example-trading-bot.mdx Set up environment variables for API key and base URL, install the necessary Python library, and then execute the trading bot script. ```bash # Set environment variables export POLYSIM_API_KEY="ps_live_..." export POLYSIM_BASE_URL="https://api.polysimulator.com" # Install dependencies pip install requests # Run python trading_bot.py ``` -------------------------------- ### Worked Example of Fee Calculation Source: https://github.com/bavariance/polysimulator-docs/blob/main/trading/fees.mdx A practical example demonstrating the fee calculation for a 10-share BUY order at $0.65 on a crypto market. ```plaintext fee = 10 × 0.07 × 0.65 × 0.35 = 0.15925 USD ``` -------------------------------- ### API Key Example Source: https://github.com/bavariance/polysimulator-docs/blob/main/authentication.mdx An example of a full PolySimulator API key and its corresponding prefix. ```text Full key | ps_live_a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2 Prefix | ps_live_a1b2c3d4 ``` -------------------------------- ### Python WebSocket Client Example Source: https://github.com/bavariance/polysimulator-docs/blob/main/websockets/price-feed.mdx An example of a Python asyncio WebSocket client connecting to the Polymarket API, including setup for API key and base URL. ```python import asyncio import json import requests import websockets API_KEY = "ps_live_..." BASE = "https://api.polysimulator.com/v1" ``` -------------------------------- ### Complete Market Data Stream Example Source: https://github.com/bavariance/polysimulator-docs/blob/main/websockets/pm-compat-market.mdx This Python example demonstrates how to connect to the PolySim market websocket, subscribe to asset data, and handle various market event types like book updates, price changes, and trades. It uses the 'websockets' library and requires an API key. ```python import asyncio import json import websockets API_KEY = "ps_live_..." ASSET_ID = "72936048731589292555781174533757608024096898681344338414570549242843090464013" async def stream(): async with websockets.connect("wss://api.polysimulator.com/v1/ws/market") as ws: await ws.send(json.dumps({ "type": "market", "assets_ids": [ASSET_ID], "auth": {"apiKey": API_KEY}, # optional on /ws/market; required on /ws/user })) async for raw in ws: evt = json.loads(raw) kind = evt.get("event_type") if kind == "book": print(f"BOOK {evt['asset_id'][:16]}... bids={len(evt['bids'])} asks={len(evt['asks'])}") elif kind == "price_change": for change in evt.get("price_changes", []): print(f"PRICE {change['asset_id'][:16]}... -> {change['price']}") elif kind == "last_trade_price": print(f"TRADE {evt['asset_id'][:16]}... {evt['side']} @ {evt['price']}") elif kind == "best_bid_ask": print(f"BBO {evt['asset_id'][:16]}... bid={evt['best_bid']} ask={evt['best_ask']}") elif kind == "error": print(f"ERROR: {evt['error']} - {evt['message']}") asyncio.run(stream()) ``` -------------------------------- ### Equity Curve Response Example Source: https://github.com/bavariance/polysimulator-docs/blob/main/account/equity-curve.mdx Example JSON response containing hourly portfolio value snapshots, including timestamp, cash balance, position value, total value, and PnL. ```json [ { "timestamp": "2026-02-06T10:00:00Z", "cash_balance": "9993.50", "position_value": "6.30", "total_value": "9999.80", "pnl": "-0.20" }, { "timestamp": "2026-02-06T11:00:00Z", "cash_balance": "9993.50", "position_value": "7.00", "total_value": "10000.50", "pnl": "0.50" } ] ``` -------------------------------- ### Get Portfolio Snapshot Source: https://github.com/bavariance/polysimulator-docs/blob/main/account/portfolio.mdx Retrieve a complete portfolio snapshot including balance, positions, and aggregate metrics. Use this to get a consolidated view of your account's status. ```bash curl -H "X-API-Key: $API_KEY" \ https://api.polysimulator.com/v1/account/portfolio ``` -------------------------------- ### Example Position Response Source: https://github.com/bavariance/polysimulator-docs/blob/main/account/positions.mdx A sample JSON response for a single open position, including market details and P&L. ```json [ { "id": 1, "market_id": "0x1a2b3c...", "outcome": "Yes", "quantity": "10.0", "avg_entry_price": "0.65", "current_price": "0.70", "market_value": "7.00", "unrealized_pnl": "0.50", "status": "OPEN", "market_question": "Will it rain tomorrow?" } ] ``` -------------------------------- ### Example Position Response with Envelope Source: https://github.com/bavariance/polysimulator-docs/blob/main/account/positions.mdx A sample JSON response for a single open position, wrapped in the Polymarket envelope format. ```json { "data": [ { "id": 1, "market_id": "0x1a2b3c...", "outcome": "Yes", "quantity": "10.0", "avg_entry_price": "0.65", "current_price": "0.70", "market_value": "7.00", "unrealized_pnl": "0.50", "status": "OPEN", "market_question": "Will it rain tomorrow?" } ], "next_cursor": "" } ``` -------------------------------- ### Get Open Positions Source: https://github.com/bavariance/polysimulator-docs/blob/main/account/positions.mdx Retrieve all open positions using the API. Ensure your API key is set in the X-API-Key header. ```bash curl -H "X-API-Key: $API_KEY" \ "https://api.polysimulator.com/v1/account/positions?status=OPEN" ``` -------------------------------- ### GET /v1/account/balance Source: https://github.com/bavariance/polysimulator-docs/blob/main/account/balance.mdx Retrieves the current API wallet balance, P&L metrics, and starting capital. API-authenticated requests read from the API wallet. ```APIDOC ## GET /v1/account/balance ### Description Returns your current API wallet balance, P&L metrics, and starting capital. API-authenticated requests always read from the API wallet. ### Method GET ### Endpoint /v1/account/balance ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -H "X-API-Key: $API_KEY" \ https://api.polysimulator.com/v1/account/balance ``` ### Response #### Success Response (200) - **balance** (string) - Current API wallet cash balance (available for trading) - **currency** (string) - Always `USD` - **starting_balance** (string) - Initial API wallet capital — your tier baseline (Pro: `10000.00`; Pro+: `25000.00`). Falls back to `10000.00` when no API wallet baseline is set. - **unrealized_pnl** (string) - Total account P&L: `total_value − starting_balance`. Despite the name, this is total equity vs starting capital (cash + open-position mark-to-market), not the open-position MTM delta alone — it equals true unrealized P&L only when `balance == starting_balance`. - **total_value** (string) - Cash balance + market value of open API positions #### Response Example ```json { "balance": "9745.20", "currency": "USD", "starting_balance": "10000.00", "unrealized_pnl": "-242.50", "total_value": "9757.50" } ``` ### Errors All errors return a JSON body of the shape `{"error": "", "message": ""}`. | Status | `error` code | When | |--------|--------------|------| | 401 | `MISSING_AUTH` | No `X-API-Key` and no `Authorization` header supplied | | 401 | `INVALID_KEY` | API key (or Bearer-wrapped key) is unknown, deactivated, or expired | | 404 | `ACCOUNT_NOT_FOUND` | Authenticated user has no account record | ``` -------------------------------- ### Place and Verify Limit Order Source: https://github.com/bavariance/polysimulator-docs/blob/main/deployment/live-migration.mdx This snippet demonstrates how to place a small test limit order and then verify the open orders using the client. Ensure you have the necessary credentials and private key configured. ```python key=os.getenv("PRIVATE_KEY"), creds=creds, ) # 1. Place a small test limit order signed = client.create_order( OrderArgs(token_id="71321045679252...", side=BUY, price=0.10, size=1) ) posted = client.post_order(signed, OrderType.GTC) print("Posted order:", posted) # 2. Verify open orders open_orders = client.get_orders() print("Open orders:", len(open_orders)) ``` -------------------------------- ### Place a Market Order (JavaScript) Source: https://github.com/bavariance/polysimulator-docs/blob/main/quickstart.mdx This JavaScript example shows how to place a market order using the fetch API. The 'price' value serves as a worst-price limit to manage slippage. Account balances are specific to the API wallet and depend on your subscription tier. ```javascript const resp = await fetch(`${process.env.POLYSIM_BASE_URL}/v1/orders`, { method: "POST", headers: { "X-API-Key": process.env.POLYSIM_API_KEY, "Content-Type": "application/json", }, body: JSON.stringify({ market_id: "0xabc123...", side: "BUY", outcome: "Yes", quantity: "10", order_type: "market", price: "0.70", // worst-price limit (slippage cap) }), }); console.log(await resp.json()); ``` -------------------------------- ### Python Example for Fetching Account Balance Source: https://github.com/bavariance/polysimulator-docs/blob/main/account/balance.mdx This Python script demonstrates how to use the requests library to fetch and process your account balance. It includes basic error handling for authentication. ```python import requests, os from decimal import Decimal BASE_URL = os.environ["POLYSIM_BASE_URL"] headers = {"X-API-Key": os.environ["POLYSIM_API_KEY"]} resp = requests.get(f"{BASE_URL}/v1/account/balance", headers=headers) if resp.status_code == 200: data = resp.json() balance = Decimal(data["balance"]) pnl = Decimal(data["total_value"]) - Decimal(data["starting_balance"]) print(f"Balance: ${balance} | P&L: ${pnl}") elif resp.status_code == 401: print("Invalid API key — check POLYSIM_API_KEY") ``` -------------------------------- ### Natural Language Summary Example Source: https://github.com/bavariance/polysimulator-docs/blob/main/account/profile-analysis.mdx An example of a human-readable summary of a trader's profile, including their trading activity, P&L, and portfolio breakdown. ```text "trader123 is a PolySimulator paper trader who joined 45 days ago. Current API balance: $9,750.00 (started at $10,000.00, P&L: -$250.00, -2.50%). Has made 127 trades across 34 markets over 22 active trading days. Win rate: 62.5%. Currently holding 5 open positions worth ~$1,100.00. Top categories: crypto (45.5%), sports (27.3%), politics (18.2%)." ``` -------------------------------- ### Connect to Execution Feed Source: https://github.com/bavariance/polysimulator-docs/blob/main/websockets/execution-feed.mdx Demonstrates how to mint a WebSocket token using cURL and then connect to the execution feed using wscat. ```bash # Mint a WS token TOKEN=$(curl -s -X POST -H "X-API-Key: $API_KEY" \ https://api.polysimulator.com/v1/keys/ws-token | jq -r '.token') # Connect wscat -c "wss://api.polysimulator.com/v1/ws/executions?token=$TOKEN" ``` -------------------------------- ### Get Open Positions Source: https://github.com/bavariance/polysimulator-docs/blob/main/bots/example-trading-bot.mdx Retrieves all currently open positions for the trading account. This function makes a GET request to the /v1/account/positions endpoint with a status filter for 'OPEN'. ```python def get_positions(): """Get all open positions.""" resp = requests.get( f"{BASE_URL}/v1/account/positions", headers=HEADERS, params={"status": "OPEN"}, ) resp.raise_for_status() return resp.json() ``` -------------------------------- ### Category Exposure JSON Example Source: https://github.com/bavariance/polysimulator-docs/blob/main/account/profile-analysis.mdx An example of the JSON structure for category exposure data, showing market categories, position counts, total values, and weight percentages. ```json [ { "category": "crypto", "position_count": 3, "total_value": "500.00", "weight_percentage": "45.5%" }, { "category": "sports", "position_count": 2, "total_value": "300.00", "weight_percentage": "27.3%" } ] ``` -------------------------------- ### Initialize Polymarket CLOB Client for Small Orders Source: https://github.com/bavariance/polysimulator-docs/blob/main/deployment/live-migration.mdx Example code to initialize the Polymarket CLOB client with live API credentials. This is used for sending small test orders to verify live execution. ```python import os from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds, OrderArgs, OrderType from py_clob_client.order_builder.constants import BUY creds = ApiCreds( api_key=os.getenv("POLY_API_KEY"), api_secret=os.getenv("POLY_API_SECRET"), api_passphrase=os.getenv("POLY_PASSPHRASE"), ) client = ClobClient( "https://clob.polymarket.com", chain_id=137, ``` -------------------------------- ### Forbidden Response Example Source: https://github.com/bavariance/polysimulator-docs/blob/main/concepts/api-keys.mdx This example shows a 403 Forbidden response with a CLOSED_BETA error code, indicating that API key issuance is in a closed beta phase and access is restricted. ```http HTTP/1.1 403 Forbidden X-Polysim-Code: CLOSED_BETA Content-Type: application/json {"error": "API access is in closed beta. New keys are issued to approved cohorts only. Apply via the waitlist; we'll email you when a cohort opens."} ``` -------------------------------- ### Backtesting with Price Candles Source: https://github.com/bavariance/polysimulator-docs/blob/main/market-data/price-candles.mdx This Python example demonstrates fetching hourly candles and calculating a simple moving average crossover for backtesting. Ensure you replace 'YOUR_API_KEY' and the market ID with your actual values. ```python import requests from decimal import Decimal BASE = "https://api.polysimulator.com" headers = {"X-API-Key": "YOUR_API_KEY"} # Fetch hourly candles for the past day. Pass outcome explicitly when # you want a specific side; default is the first outcome. candles = requests.get( f"{BASE}/v1/markets/0x0f49.../candles", headers=headers, params={"interval": "1h", "outcome": "Yes"}, ).json() # Simple moving average crossover (close prices) prices = [Decimal(c["c"]) for c in candles] if len(prices) >= 48: sma_short = sum(prices[-12:]) / 12 # last 12 hours sma_long = sum(prices[-48:]) / 48 # last 48 hours if sma_short > sma_long: print("Bullish crossover — consider BUY") else: print("Bearish crossover — consider SELL") ``` -------------------------------- ### Go: Handling String Numerics with shopspring/decimal Source: https://github.com/bavariance/polysimulator-docs/blob/main/concepts/string-numerics.mdx Illustrates how to use the shopspring/decimal library in Go to parse string-formatted numeric values from API responses and perform precise calculations. ```go import "github.com/shopspring/decimal" price, _ := decimal.NewFromString(order.Price) qty, _ := decimal.NewFromString(order.Quantity) notional := price.Mul(qty) // "6.50" ``` -------------------------------- ### Place a Market Order (Python) Source: https://github.com/bavariance/polysimulator-docs/blob/main/quickstart.mdx This Python script demonstrates how to place a market order using the requests library. The 'price' parameter acts as a worst-price limit for slippage control. Note that API keys have different wallet balances based on the tier. ```python import requests, os resp = requests.post( f"{os.environ['POLYSIM_BASE_URL']}/v1/orders", headers={ "X-API-Key": os.environ["POLYSIM_API_KEY"], "Content-Type": "application/json", }, json={ "market_id": "0xabc123...", "side": "BUY", "outcome": "Yes", "quantity": "10", "order_type": "market", "price": "0.70", # worst-price limit (slippage cap) }, ) print(resp.json()) ``` -------------------------------- ### GET /v1/order/{orderID} - Get single order Source: https://github.com/bavariance/polysimulator-docs/blob/main/concepts/pm-raw-http.mdx Retrieves details for a specific order using its ID. Returns an `OpenOrder` object, similar in shape to the items in the `data` array from the list orders endpoint. ```APIDOC ## GET /v1/order/{orderID} ### Description Retrieves details for a specific order using its ID. Returns an `OpenOrder` object, similar in shape to the items in the `data` array from the list orders endpoint. ### Method GET ### Endpoint https://api.polysimulator.com/v1/order/{orderID} ### Parameters #### Path Parameters - **orderID** (string) - Required - The ID of the order to retrieve. Can be a hex order ID or an integer DB ID serialized as a string. ### Response #### Success Response (200) Returns an `OpenOrder` object with the same shape as the items in the `data` array from the `GET /v1/data/orders` endpoint. #### Response Example ```json { "id": "6390", "status": "ORDER_STATUS_FILLED", "owner": "your-api-key-uuid", "maker_address": null, "market": "0x0f49db97...", "asset_id": null, "side": "BUY", "original_size": "1.0000", "size_matched": "0.2480", "price": "0.5000", "outcome": "Yes", "expiration": "0", "order_type": "GTC", "associate_trades": [], "created_at": 1778103749 } ``` ``` -------------------------------- ### Virtual vs. Live Order Placement Source: https://github.com/bavariance/polysimulator-docs/blob/main/concepts/clob-compatibility.mdx Demonstrates how to place a GTC BUY order using both the PolySimulator virtual endpoint and the live Polymarket CLOB client. The core order payload remains the same, but authentication and client setup differ significantly. ```python import requests BASE = "https://api.polysimulator.com/v1" headers = {"X-API-Key": "ps_live_kJ9mNx2p..."} order = requests.post(f"{BASE}/clob/order", headers=headers, json={ "token_id": "71321045679252...", "side": "BUY", "price": "0.65", "size": "10", "order_type": "GTC", }).json() ``` ```python from py_clob_client.client import ClobClient client = ClobClient("https://clob.polymarket.com", key=PRIVATE_KEY, chain_id=137) client.set_api_creds(client.create_or_derive_api_key()) # Same order payload — only auth + client changes order = client.create_and_post_order(OrderArgs( token_id="71321045679252...", side="BUY", price=0.65, size=10, order_type="GTC", )) ``` -------------------------------- ### GET /v1/account/portfolio Source: https://github.com/bavariance/polysimulator-docs/blob/main/llms.txt Retrieves an aggregate portfolio snapshot. ```APIDOC ## GET /v1/account/portfolio ### Description Retrieves an aggregate snapshot of the user's portfolio. ### Method GET ### Endpoint /v1/account/portfolio ### Parameters #### Query Parameters - **wallet_id** (string or integer) - Optional - Filter by wallet ID. Accepts an integer ID, 'all', or 'api'. Defaults to 'api'. ``` -------------------------------- ### GET /v1/orders Source: https://github.com/bavariance/polysimulator-docs/blob/main/llms.txt Retrieves a list of orders based on specified filters. ```APIDOC ## GET /v1/orders ### Description Retrieves a list of orders with optional filtering and pagination. ### Method GET ### Endpoint /v1/orders ### Parameters #### Query Parameters - **status** (string) - Optional - Filter orders by status. - **market_id** (string) - Optional - Filter orders by market ID. - **side** (string) - Optional - Filter orders by side ('BUY' or 'SELL'). - **limit** (integer) - Optional - The maximum number of orders to return. - **offset** (integer) - Optional - The number of orders to skip. - **cursor** (string) - Optional - A cursor for paginating through results. ``` -------------------------------- ### Python SDK: Configure API Credentials Source: https://github.com/bavariance/polysimulator-docs/blob/main/concepts/pm-raw-http.mdx Example of configuring the PolySim Python SDK client with the API host and credentials. Note that 'chain_id' and 'key' are ignored by the server, and API credentials should be set separately. ```python from py_clob_client.client import ClobClient client = ClobClient( host="https://api.polysimulator.com", # was clob.polymarket.com chain_id=137, # leave as-is (ignored) key="", # leave as-is (ignored) ) client.set_api_creds({"X-API-Key": "ps_live_..."}) ``` -------------------------------- ### Place Order using PolySimulator (Virtual Mode) Source: https://github.com/bavariance/polysimulator-docs/blob/main/deployment/live-migration.mdx Example of placing an order using the PolySimulator's virtual CLOB API. It uses a simple X-API-Key header for authentication. ```python import requests, os BASE_URL = os.environ["POLYSIM_BASE_URL"] # https://api.polysimulator.com/v1 headers = {"X-API-Key": os.environ["POLYSIM_API_KEY"]} order = requests.post(f"{BASE_URL}/clob/order", headers=headers, json={ "token_id": "71321045679252...", "side": "BUY", "price": "0.65", "size": "10", "order_type": "GTC", }) order.raise_for_status() print(order.json()) ``` -------------------------------- ### Python: Handling Legacy Float Price from /markets/updown Source: https://github.com/bavariance/polysimulator-docs/blob/main/concepts/string-numerics.mdx Shows how to defensively parse the 'live_price.buy' and 'live_price.sell' fields from the legacy /markets/updown endpoint, which are floats, and convert them to Decimal for accurate calculations. ```python buy = float(market["live_price"]["buy"]) # float here, str everywhere else from decimal import Decimal buy_dec = Decimal(str(market["live_price"]["buy"])) ``` -------------------------------- ### GET /v1/account/equity Source: https://github.com/bavariance/polysimulator-docs/blob/main/llms.txt Retrieves hourly equity snapshots for a specified number of days. ```APIDOC ## GET /v1/account/equity ### Description Retrieves hourly equity snapshots for the account over a specified period. ### Method GET ### Endpoint /v1/account/equity ### Parameters #### Query Parameters - **days** (integer) - Required - The number of past days to retrieve equity snapshots for. - **wallet_id** (string or integer) - Optional - Filter by wallet ID. Accepts an integer ID, 'all', or 'api'. Defaults to 'api'. ``` -------------------------------- ### GET /v1/account/positions Source: https://github.com/bavariance/polysimulator-docs/blob/main/llms.txt Retrieves a list of open and closed positions, with optional filtering. ```APIDOC ## GET /v1/account/positions ### Description Retrieves a list of open and closed positions. Supports filtering by status and wallet ID. ### Method GET ### Endpoint /v1/account/positions ### Parameters #### Query Parameters - **status** (string) - Optional - Filter positions by status (e.g., 'open', 'closed'). - **wallet_id** (string or integer) - Optional - Filter by wallet ID. Accepts an integer ID, 'all', or 'api'. Defaults to 'api'. - **envelope** (boolean) - Optional - Whether to return results in an envelope format. ``` -------------------------------- ### Set Up PolySimulator Environment Variables Source: https://github.com/bavariance/polysimulator-docs/blob/main/bots/best-practices.mdx Configure environment variables for paper trading on PolySimulator. This includes setting the base URL and API key for the simulation environment. ```bash # Paper trading on PolySimulator export POLYSIM_BASE_URL="https://api.polysimulator.com" export POLYSIM_API_KEY="ps_live..." ``` -------------------------------- ### GET /v1/order/{order_id} Source: https://github.com/bavariance/polysimulator-docs/blob/main/llms.txt Retrieves a single order by its ID in Polymarket shape. ```APIDOC ## GET /v1/order/{order_id} ### Description Retrieves a single order by its unique identifier in the Polymarket shape. ### Method GET ### Endpoint /v1/order/{order_id} ### Parameters #### Path Parameters - **order_id** (string) - Required - The ID of the order to retrieve. ### Response #### Success Response (200) - Returns the order in Polymarket shape. See GET /v1/data/orders for the shape details. ``` -------------------------------- ### GET /v1/data/trades Source: https://github.com/bavariance/polysimulator-docs/blob/main/llms.txt Retrieves filled order data in Polymarket-compat format for trade tracking. ```APIDOC ## GET /v1/data/trades ### Description Retrieves filled order data in a Polymarket-compat format. This endpoint is used by py-clob-client for tracking fills and emits PM-shape trade rows. ### Method GET ### Endpoint /v1/data/trades ### Parameters #### Query Parameters - **market** (string) - Optional - Filter trades by market ID. - **asset_id** (string) - Optional - Filter trades by asset ID. - **before** (integer) - Optional - Filter trades before a specific timestamp. - **after** (integer) - Optional - Filter trades after a specific timestamp. - **cursor** (string) - Optional - Cursor for paginating through results (same as used in /v1/data/orders). ``` -------------------------------- ### Place Limit Order and Listen for Fills Source: https://github.com/bavariance/polysimulator-docs/blob/main/websockets/execution-feed.mdx A Python example showing how to place a limit order using the REST API and then connect to the WebSocket to listen for fill notifications. Use `client_order_id` to correlate fills with your orders. ```python import asyncio import json import requests import websockets API_KEY = "ps_live_..." BASE = "https://api.polysimulator.com/v1" headers = {"X-API-Key": API_KEY} # 1. Place a limit order order = requests.post(f"{BASE}/orders", headers=headers, json={ "market_id": "0x1a2b3c...", "side": "BUY", "outcome": "Yes", "quantity": "10", "order_type": "limit", "price": "0.60", "time_in_force": "GTC", "client_order_id": "limit-001", }).json() print(f"Limit order placed: {order['status']}") # 2. Listen for fills ws_token = requests.post( f"{BASE}/keys/ws-token", headers=headers ).json()["token"] async def listen_fills(): async with websockets.connect( f"wss://api.polysimulator.com/v1/ws/executions?token={ws_token}" ) as ws: async for raw in ws: msg = json.loads(raw) # Fill frames are FLAT (no `data` wrapper) and use type == "fill". if msg.get("type") == "fill": print(f"Filled: {msg['side']} {msg['quantity']}x {msg['outcome']} @ {msg['price']}") asyncio.run(listen_fills()) ``` -------------------------------- ### Initialize Polymarket CLOB Trading Client Source: https://github.com/bavariance/polysimulator-docs/blob/main/llms.txt Initializes the ClobClient with API credentials and funding wallet information for live trading on Polymarket. ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import ApiCreds import os api_creds = ApiCreds( api_key=os.getenv("POLY_API_KEY"), api_secret=os.getenv("POLY_API_SECRET"), api_passphrase=os.getenv("POLY_PASSPHRASE"), ) client = ClobClient( host="https://clob.polymarket.com", key=os.getenv("PRIVATE_KEY"), chain_id=137, creds=api_creds, signature_type=0, # 0=EOA wallet, 1=MagicLink, 2=browser proxy funder=os.getenv("FUNDER_ADDRESS"), # wallet paying gas + holding USDC.e ) ``` -------------------------------- ### Get Account Positions (All Wallets) Source: https://github.com/bavariance/polysimulator-docs/blob/main/account/wallets.mdx Retrieves positions for all owned wallets by specifying wallet_id=all. ```APIDOC ## GET /v1/account/positions?wallet_id=all ### Description Retrieves positions for all owned wallets by specifying wallet_id=all. ### Method GET ### Endpoint /v1/account/positions?wallet_id=all ### Parameters #### Query Parameters - **wallet_id** (string) - Required - Set to `all` to retrieve positions for all wallets. ### Request Example ```bash curl -H "X-API-Key: $POLYSIM_API_KEY" \ "https://api.polysimulator.com/v1/account/positions?wallet_id=all" ``` ### Response #### Success Response (200) - **positions** (array) - A list of the user's positions across all wallets. #### Response Example ```json { "positions": [ { "symbol": "BTC", "amount": 1.5, "value": 50000 }, { "symbol": "ETH", "amount": 10, "value": 30000 } ] } ``` ``` -------------------------------- ### List Markets (Back-Compat Default) Source: https://github.com/bavariance/polysimulator-docs/blob/main/market-data/markets.mdx Fetches a list of markets using the default bare-array response format. Useful for direct API integration. ```bash curl -H "X-API-Key: $API_KEY" \ "https://api.polysimulator.com/v1/markets?hot_only=true&limit=10" ``` -------------------------------- ### Receive Price Message from WebSocket Source: https://github.com/bavariance/polysimulator-docs/blob/main/llms.txt This is an example of the price message format received from the WebSocket stream. ```json {"type": "price", "market_id": "cond-123", "buy": "0.65", "sell": "0.35", "best_bid": "0.64", "best_ask": "0.66", "volume": "1000.00", "source": "clob", "updated_at": "..."} ``` -------------------------------- ### GET /v1/data/orders Source: https://github.com/bavariance/polysimulator-docs/blob/main/llms.txt Retrieves Polymarket open orders in an envelope format, including pagination details. ```APIDOC ## GET /v1/data/orders ### Description Retrieves Polymarket open orders in an envelope format, which includes pagination information and a list of orders. ### Method GET ### Endpoint /v1/data/orders ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of orders to return. - **count** (integer) - Optional - The total count of orders. - **next_cursor** (string) - Optional - A URL-safe base64 encoded cursor for the next page of results. - **data** (array) - Optional - An array of Polymarket OpenOrder shapes. - **id** (string) - Order ID. - **status** (string) - Order status. - **owner** (string) - Order owner. - **maker_address** (string) - Maker's address. - **market** (string) - Market ID. - **asset_id** (string) - Asset ID. - **original_size** (number) - Original order size. - **size_matched** (number) - Matched order size. - **price** (number) - Order price. - **outcome** (string) - Market outcome. - **expiration** (integer) - Order expiration timestamp. - **order_type** (string) - Type of order. - **associate_trades** (array) - Associated trades. - **created_at** (integer) - Creation timestamp. ``` -------------------------------- ### Bootstrap API Key Creation using Python Source: https://github.com/bavariance/polysimulator-docs/blob/main/llms.txt This Python script demonstrates how to obtain your first API key by calling the /v1/keys/bootstrap endpoint. Ensure you have your Supabase JWT from polysimulator.com. ```python import requests supabase_jwt = "your_supabase_access_token" # from polysimulator.com sign-in resp = requests.post( "https://api.polysimulator.com/v1/keys/bootstrap", headers={"Authorization": f"Bearer {supabase_jwt}", "Content-Type": "application/json"}, json={"name": "my-bot"}, # optional ) resp.raise_for_status() raw_key = resp.json()["raw_key"] # save this — shown only once ``` -------------------------------- ### Get Hot Markets Source: https://github.com/bavariance/polysimulator-docs/blob/main/market-data/markets.mdx Retrieves a list of markets that are currently experiencing high trading volume. ```APIDOC ## GET /v1/markets ### Description Retrieves a list of markets, with an option to filter for only 'hot' markets (those with trading volume exceeding $5,000). ### Method GET ### Endpoint /v1/markets ### Parameters #### Query Parameters - **hot_only** (bool) - Optional - Filter for actively traded markets (`is_hot: true`). Recommended for bots to ensure sufficient liquidity. ### Response #### Success Response (200) - A list of market objects. Each market object may contain an `is_hot` field (boolean) indicating if it meets the hot market criteria. ### Request Example ```bash # Only hot markets curl -H "X-API-Key: $API_KEY" \ "https://api.polysimulator.com/v1/markets?hot_only=true" ``` ``` -------------------------------- ### Fetch Prices for Open Positions using Python Source: https://github.com/bavariance/polysimulator-docs/blob/main/market-data/batch-prices.mdx This Python script demonstrates how to fetch prices for all open positions. It first retrieves open positions, extracts their market IDs, and then makes a batch price request. It handles cases where prices might be unavailable. ```python import requests API_KEY = "ps_live_..." BASE = "https://api.polysimulator.com" headers = {"X-API-Key": API_KEY} # Fetch prices for all open positions positions = requests.get( f"{BASE}/v1/account/positions", headers=headers, params={"status": "OPEN"}, ).json() market_ids = [p["market_id"] for p in positions] prices = requests.post( f"{BASE}/v1/prices/batch", headers=headers, json={"market_ids": market_ids}, ).json() for p in prices: if p.get("buy") is not None: print(f"{p['condition_id'][:16]}: Yes={p['buy']}, No={p['sell']}") else: print(f"{p['condition_id'][:16]}: price unavailable") ``` -------------------------------- ### GET /v1/data/order/{order_id} Source: https://github.com/bavariance/polysimulator-docs/blob/main/llms.txt Retrieves a single order by its ID in Polymarket-compat canonical nested path format. ```APIDOC ## GET /v1/data/order/{order_id} ### Description Retrieves a single order by its ID using the Polymarket-compat canonical nested path. This is the format currently used by py-clob-client. ### Method GET ### Endpoint /v1/data/order/{order_id} ### Parameters #### Path Parameters - **order_id** (string) - Required - The ID of the order to retrieve. ### Response #### Success Response (200) - Returns the order in Polymarket OpenOrder shape. See GET /v1/data/orders for the shape details. ``` -------------------------------- ### Get Rate Limit Tiers Source: https://github.com/bavariance/polysimulator-docs/blob/main/llms.txt Retrieves information about the available rate limit tiers and their associated limits. ```APIDOC ## GET /v1/keys/tiers ### Description Retrieves the authoritative source for rate limit tiers and their specifications. ### Method GET ### Endpoint /v1/keys/tiers ### Response #### Success Response (200 OK) - **rate_limit_tier** (string) - The name of the rate limit tier (e.g., "free", "pro", "pro_plus", "enterprise"). - **req_sec_burst** (integer) - The burst request rate limit per second. - **req_min_sustained** (integer) - The sustained request rate limit per minute. - **websocket_connections** (integer) - The maximum number of WebSocket connections allowed. - **batch_size** (integer) - The maximum batch size for requests. #### Response Example (Note: Actual response structure may vary, this is illustrative) ```json [ { "rate_limit_tier": "free", "req_sec_burst": 2, "req_min_sustained": 120, "websocket_connections": 1, "batch_size": 1 }, { "rate_limit_tier": "pro", "req_sec_burst": 10, "req_min_sustained": 600, "websocket_connections": 3, "batch_size": 5 } ] ``` ``` -------------------------------- ### Bootstrap API Key from Script Source: https://github.com/bavariance/polysimulator-docs/blob/main/authentication.mdx For headless or CI environments, you can bootstrap an API key by calling POST /v1/keys/bootstrap directly if you have a Supabase access token. This is an alternative to using the dashboard. ```python import requests # Obtain via a programmatic Supabase sign-in — most users don't ```