[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71H2JK04HXMR09RKPW12PXS":3,"skill-same:01M71H2JK04HXMR09RKPW12PXS":74},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":35,"linkOnly":36,"markdownContent":37,"markdownBody":38,"frontMatter":39,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":50,"repositoryHtmlUrl":51,"repositoryHomepageUrl":6,"ownerHtmlUrl":52,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":53,"install":54,"resources":67},"01M71H2JK04HXMR09RKPW12PXS","trading-polymarket",null,"Execute trades on Polymarket using py_clob_client - full API access for market data, orders, positions","JSGforever\u002Fskillguard","JSGforever","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F85541948?v=4","01M71FQD3E132VMR5F4TAYX3YS","01M71FQD4DYW0XJ4XQ4YQH75Y9",2,"GPL-3.0","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__alsk1992--trading-polymarket\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"polymarket","trading","trading polymarket","execute","client","Market","passphrase","for","full","orders","positions","data","market data","api","access","secret","clob","2026-11-10 10:12:30",false,"---\nname: trading-polymarket\ndescription: \"Execute trades on Polymarket using py_clob_client - full API access for market data, orders, positions\"\nemoji: \"💰\"\ngates:\n  envs:\n    - POLY_API_KEY\n    - POLY_API_SECRET\n    - POLY_API_PASSPHRASE\n    - PRIVATE_KEY\n---\n\n# Polymarket Trading - Complete API Reference\n\nFull access to Polymarket's CLOB (Central Limit Order Book) via the official `py_clob_client` library.\n\n**60+ methods documented. This is the complete reference.**\n\n## Required Environment Variables\n\n```bash\nPRIVATE_KEY=0x...           # Ethereum private key for signing\nPOLY_FUNDER_ADDRESS=0x...   # Your wallet address on Polygon\nPOLY_API_KEY=...            # From Polymarket API\nPOLY_API_SECRET=...         # Base64 encoded secret\nPOLY_API_PASSPHRASE=...     # API passphrase\n```\n\n## Installation\n\n```bash\npip install py-clob-client requests\n```\n\n---\n\n## Authentication Levels\n\n| Level | Requirements | Capabilities |\n|-------|--------------|--------------|\n| **L0** | None | Read-only: orderbooks, prices, markets |\n| **L1** | Private key | Create & sign orders (not post) |\n| **L2** | Private key + API creds | Full trading: post orders, cancel, query |\n\n### Signature Types\n\n| Type | Use Case |\n|------|----------|\n| `0` | Standard EOA (MetaMask, hardware wallets) |\n| `1` | Magic\u002Femail wallets (delegated signing) |\n| `2` | Proxy wallets (Gnosis Safe, browser proxy) |\n\n---\n\n## ClobClient - Complete API (60+ Methods)\n\n### Initialization\n\n```python\nfrom py_clob_client.client import ClobClient\nfrom py_clob_client.clob_types import (\n    OrderArgs, MarketOrderArgs, ApiCreds, OrderType,\n    BookParams, TradeParams, OpenOrderParams, BalanceAllowanceParams,\n    AssetType, OrderScoringParams, OrdersScoringParams, DropNotificationParams\n)\nfrom py_clob_client.order_builder.constants import BUY, SELL\nfrom py_clob_client.constants import POLYGON  # 137\n\n# Level 2 Auth (full trading access)\nclient = ClobClient(\n    host=\"https:\u002F\u002Fclob.polymarket.com\",\n    key=os.getenv(\"PRIVATE_KEY\"),           # Private key for signing\n    chain_id=POLYGON,                        # 137 for mainnet, 80002 for Amoy testnet\n    funder=os.getenv(\"POLY_FUNDER_ADDRESS\"), # Wallet address (for proxy wallets)\n    signature_type=2                         # 0=EOA, 1=MagicLink, 2=Proxy\n)\n\n# Set API credentials for authenticated endpoints\nclient.set_api_creds(ApiCreds(\n    api_key=os.getenv(\"POLY_API_KEY\"),\n    api_secret=os.getenv(\"POLY_API_SECRET\"),\n    api_passphrase=os.getenv(\"POLY_API_PASSPHRASE\")\n))\n```\n\n### Health & Configuration\n\n```python\nclient.get_ok()                    # Check if server is up\nclient.get_server_time()           # Get server timestamp\nclient.get_address()               # Your signer's public address\nclient.get_collateral_address()    # USDC contract address\nclient.get_conditional_address()   # CTF contract address\nclient.get_exchange_address()      # Exchange contract (neg_risk=False default)\n```\n\n### Market Data - Single Token\n\n```python\n# Get prices and spreads\nclient.get_midpoint(token_id)              # Mid market price\nclient.get_price(token_id, side=\"BUY\")     # Best price for side\nclient.get_spread(token_id)                # Current spread\nclient.get_last_trade_price(token_id)      # Last executed trade price\n\n# Get full orderbook\norderbook = client.get_order_book(token_id)\n# Returns: OrderBookSummary with bids, asks, tick_size, neg_risk, timestamp, hash\n```\n\n### Market Data - Batch (Multiple Tokens)\n\n```python\nparams = [\n    BookParams(token_id=\"TOKEN1\", side=\"BUY\"),\n    BookParams(token_id=\"TOKEN2\", side=\"SELL\")\n]\n\nclient.get_midpoints(params)           # Multiple midpoints\nclient.get_prices(params)              # Multiple prices\nclient.get_spreads(params)             # Multiple spreads\nclient.get_order_books(params)         # Multiple orderbooks\nclient.get_last_trades_prices(params)  # Multiple last prices\n```\n\n### Market Metadata\n\n```python\nclient.get_tick_size(token_id)      # Returns: \"0.1\", \"0.01\", \"0.001\", or \"0.0001\"\nclient.get_neg_risk(token_id)       # Returns: True\u002FFalse (negative risk market)\nclient.get_fee_rate_bps(token_id)   # Returns: fee rate in basis points (0 or 1000)\n```\n\n---\n\n## Order Types\n\n```python\nfrom py_clob_client.clob_types import OrderType\n\nOrderType.GTC   # Good Till Cancelled - stays open until filled\u002Fcancelled\nOrderType.FOK   # Fill Or Kill - fill entirely immediately or cancel\nOrderType.GTD   # Good Till Date - expires at timestamp (min 60 seconds)\nOrderType.FAK   # Fill And Kill - fill what's possible, cancel rest\n```\n\n### When to Use Each Order Type\n\n| Type | Use Case | Example |\n|------|----------|---------|\n| **GTC** | Entries - wait for fill | Place buy at 0.45, wait for dip |\n| **FOK** | Exits - need immediate fill | Market sell entire position NOW |\n| **GTD** | Time-limited orders | Offer expires in 5 minutes |\n| **FAK** | Partial fills OK | Get as much as possible now |\n\n### OrderArgs - Limit Orders\n\n```python\nOrderArgs(\n    token_id: str,           # Token ID (outcome to trade)\n    price: float,            # Price 0.01-0.99\n    size: float,             # Number of shares\n    side: str,               # \"BUY\" or \"SELL\" (or use BUY\u002FSELL constants)\n    fee_rate_bps: int = 0,   # Optional: fee rate in bps (0 or check market)\n    nonce: int = 0,          # Optional: unique nonce for cancellation\n    expiration: int = 0,     # Optional: expiry timestamp (0 = GTC, use timestamp for GTD)\n    taker: str = ZERO_ADDRESS  # Optional: specific taker (ZERO_ADDRESS = anyone)\n)\n```\n\n### MarketOrderArgs - Market Orders\n\n```python\nMarketOrderArgs(\n    token_id: str,           # Token ID\n    amount: float,           # Total USDC amount to spend (BUY) or shares (SELL)\n    side: str,               # \"BUY\" or \"SELL\"\n    price: float = 0,        # Optional: worst acceptable price (slippage protection)\n    fee_rate_bps: int = 0,   # Optional: fee rate\n    nonce: int = 0,          # Optional: nonce\n    taker: str = ZERO_ADDRESS,  # Optional: taker address\n    order_type: OrderType = FOK  # Optional: FOK (default) or FAK\n)\n```\n\n### Complete Order Examples\n\n```python\nfrom py_clob_client.order_builder.constants import BUY, SELL\n\n# 1. LIMIT BUY (GTC) - sits on book until filled\norder = client.create_and_post_order(\n    OrderArgs(token_id=TOKEN_ID, price=0.45, size=100.0, side=BUY)\n)\n\n# 2. LIMIT SELL (GTC)\norder = client.create_and_post_order(\n    OrderArgs(token_id=TOKEN_ID, price=0.55, size=50.0, side=SELL)\n)\n\n# 3. MARKET BUY - spend $100 USDC at current prices (FOK)\nsigned = client.create_market_order(\n    MarketOrderArgs(token_id=TOKEN_ID, amount=100.0, side=BUY)\n)\nresult = client.post_order(signed, orderType=OrderType.FOK)\n\n# 4. MARKET SELL - sell all shares immediately (FOK)\nsigned = client.create_market_order(\n    MarketOrderArgs(token_id=TOKEN_ID, amount=my_shares, side=SELL)\n)\nresult = client.post_order(signed, orderType=OrderType.FOK)\n\n# 5. POST-ONLY MAKER ORDER (avoid taker fees, earn rebates)\nsigned = client.create_order(\n    OrderArgs(token_id=TOKEN_ID, price=0.44, size=100.0, side=BUY)\n)\nresult = client.post_order(signed, orderType=OrderType.GTC, post_only=True)\n# If order would cross spread, it gets REJECTED instead of taking\n\n# 6. GOOD TIL DATE (GTD) - expires after timestamp\nimport time\nexpiry = int(time.time()) + 300  # 5 minutes from now\nsigned = client.create_order(\n    OrderArgs(token_id=TOKEN_ID, price=0.50, size=100.0, side=BUY, expiration=expiry)\n)\nresult = client.post_order(signed, orderType=OrderType.GTD)\n\n# 7. FILL AND KILL (FAK) - fill what you can, cancel rest\nsigned = client.create_market_order(\n    MarketOrderArgs(token_id=TOKEN_ID, amount=1000.0, side=BUY)\n)\nresult = client.post_order(signed, orderType=OrderType.FAK)\n```\n\n---\n\n## Order Operations\n\n### Create and Post Orders\n\n```python\n# SIMPLE: Create and post in one call (recommended)\nresult = client.create_and_post_order(\n    OrderArgs(\n        token_id=\"123456789012345678901234567890\",\n        price=0.45,\n        size=10.0,\n        side=\"BUY\"\n    )\n)\n# Returns: {\"orderID\": \"...\", \"status\": \"...\", ...}\n\n# ADVANCED: Separate create and post\norder = client.create_order(OrderArgs(...))  # Returns SignedOrder\nresult = client.post_order(order, orderType=OrderType.GTC, post_only=False)\n\n# Market order (calculates price automatically)\nresult = client.create_market_order(\n    MarketOrderArgs(\n        token_id=\"...\",\n        amount=100.0,    # Spend $100 USDC\n        side=\"BUY\"\n    )\n)\n\n# Calculate expected fill price before market order\nprice = client.calculate_market_price(\n    token_id=\"...\",\n    side=\"BUY\",\n    amount=100.0,\n    order_type=OrderType.FOK\n)\n```\n\n### Cancel Orders\n\n```python\nclient.cancel(order_id=\"ORDER_ID\")           # Cancel specific order\nclient.cancel_orders([\"ID1\", \"ID2\", \"ID3\"])  # Cancel multiple\nclient.cancel_all()                          # Cancel ALL open orders\nclient.cancel_market_orders(                 # Cancel by market\u002Fasset\n    market=\"CONDITION_ID\",\n    asset_id=\"TOKEN_ID\"\n)\n```\n\n### Query Orders\n\n```python\n# Get all open orders\norders = client.get_orders(\n    params=OpenOrderParams(\n        id=\"ORDER_ID\",      # Optional: specific order\n        market=\"COND_ID\",   # Optional: filter by market\n        asset_id=\"TOKEN\"    # Optional: filter by token\n    ),\n    next_cursor=\"MA==\"      # For pagination\n)\n\n# Get specific order\norder = client.get_order(order_id=\"ORDER_ID\")\n```\n\n### Trade History\n\n```python\ntrades = client.get_trades(\n    params=TradeParams(\n        id=\"TRADE_ID\",           # Optional: specific trade\n        maker_address=\"0x...\",   # Optional: filter by maker\n        market=\"CONDITION_ID\",   # Optional: filter by market\n        asset_id=\"TOKEN_ID\",     # Optional: filter by token\n        before=\"2024-01-01\",     # Optional: before date\n        after=\"2023-01-01\"       # Optional: after date\n    ),\n    next_cursor=\"MA==\"\n)\n```\n\n### Balance & Allowance\n\n```python\n# Check balance and allowances\nbalance = client.get_balance_allowance(\n    params=BalanceAllowanceParams(\n        asset_type=AssetType.COLLATERAL,  # USDC balance\n        # or AssetType.CONDITIONAL         # Token balance\n        token_id=\"TOKEN_ID\"                # For conditional tokens\n    )\n)\n\n# Update\u002Frefresh allowance cache\nclient.update_balance_allowance(params=...)\n```\n\n---\n\n## Market Discovery\n\n### Get Markets from CLOB\n\n```python\n# All active markets\nmarkets = client.get_markets(next_cursor=\"MA==\")\nsimplified = client.get_simplified_markets()\n\n# Specific market\nmarket = client.get_market(condition_id=\"CONDITION_ID\")\n\n# Market trade events\nevents = client.get_market_trades_events(condition_id=\"CONDITION_ID\")\n\n# Sampling\u002Ffeatured markets\nclient.get_sampling_markets()\nclient.get_sampling_simplified_markets()\n```\n\n### Get Markets from Gamma API (More Details)\n\n```python\nimport requests\n\ndef search_markets(query: str, limit: int = 10):\n    \"\"\"Search Polymarket markets by keyword\"\"\"\n    url = \"https:\u002F\u002Fgamma-api.polymarket.com\u002Fmarkets\"\n    params = {\n        \"_q\": query,\n        \"active\": \"true\",\n        \"closed\": \"false\",\n        \"_limit\": limit\n    }\n    r = requests.get(url, params=params)\n    return r.json()\n\n# Get market details\nmarkets = search_markets(\"bitcoin\")\nfor m in markets:\n    print(f\"Question: {m['question']}\")\n    print(f\"Condition ID: {m['condition_id']}\")\n    print(f\"Volume: ${m.get('volume', 0):,.2f}\")\n    for token in m.get('tokens', []):\n        print(f\"  {token['outcome']}: {token['token_id']}\")\n        print(f\"    Price: {float(token['price']):.2f}\")\n```\n\n---\n\n## On-Chain Operations\n\n### Check Token Balance (Position Size)\n\n```python\nimport requests\n\nCTF_CONTRACT = \"0x4D97DCd97eC945f40cF65F87097ACe5EA0476045\"\nRPC_URL = \"https:\u002F\u002Fpolygon-rpc.com\u002F\"\n\ndef get_token_balance(wallet: str, token_id: str) -> float:\n    \"\"\"Get balance of a specific outcome token in shares\"\"\"\n    token_int = int(token_id)\n    # ERC-1155 balanceOf(address,uint256)\n    data = f\"0x00fdd58e000000000000000000000000{wallet[2:].lower()}{token_int:064x}\"\n\n    r = requests.post(RPC_URL, json={\n        \"jsonrpc\": \"2.0\",\n        \"method\": \"eth_call\",\n        \"params\": [{\"to\": CTF_CONTRACT, \"data\": data}, \"latest\"],\n        \"id\": 1\n    })\n\n    result = r.json().get(\"result\", \"0x0\")\n    balance = int(result, 16) \u002F 1e6  # Convert from raw to shares\n    return balance\n\n# Usage\nbalance = get_token_balance(\n    wallet=\"0x7c2211103e7Fbb257Ac6fa59f972cfd8bc9D4795\",\n    token_id=\"12345678901234567890\"\n)\nprint(f\"Position: {balance} shares\")\n```\n\n### Check USDC Balance\n\n```python\nUSDC_CONTRACT = \"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174\"\n\ndef get_usdc_balance(wallet: str) -> float:\n    \"\"\"Get USDC balance on Polygon\"\"\"\n    # ERC-20 balanceOf(address)\n    data = f\"0x70a08231000000000000000000000000{wallet[2:].lower()}\"\n\n    r = requests.post(RPC_URL, json={\n        \"jsonrpc\": \"2.0\",\n        \"method\": \"eth_call\",\n        \"params\": [{\"to\": USDC_CONTRACT, \"data\": data}, \"latest\"],\n        \"id\": 1\n    })\n\n    result = r.json().get(\"result\", \"0x0\")\n    return int(result, 16) \u002F 1e6  # USDC has 6 decimals\n```\n\n---\n\n## API Key Management\n\n```python\n# Create new API key\ncreds = client.create_api_key(nonce=0)\n\n# Derive existing API key (if you lost creds but have private key)\ncreds = client.derive_api_key(nonce=0)\n\n# Create or derive (tries both)\ncreds = client.create_or_derive_api_creds(nonce=0)\n\n# Get all your API keys\nkeys = client.get_api_keys()\n\n# Delete current API key\nclient.delete_api_key()\n\n# Readonly API keys (for monitoring only)\nreadonly = client.create_readonly_api_key()\nclient.get_readonly_api_keys()\nclient.delete_readonly_api_key(key=\"...\")\nclient.validate_readonly_api_key(address=\"0x...\", key=\"...\")\n```\n\n---\n\n## Advanced Features\n\n### Order Heartbeat (Keep Orders Alive)\n\n```python\n# Start heartbeat - if not sent within 10s, all orders cancelled\nheartbeat_id = client.post_heartbeat(heartbeat_id=None)\n\n# Continue sending heartbeats\nwhile trading:\n    client.post_heartbeat(heartbeat_id=heartbeat_id)\n    time.sleep(5)\n```\n\n### Order Scoring\n\n```python\n# Check if order is scoring (earning rewards)\nis_scoring = client.is_order_scoring(\n    params=OrderScoringParams(order_id=\"...\")\n)\n\n# Check multiple orders\nscores = client.are_orders_scoring(\n    params=OrdersScoringParams(order_ids=[\"ID1\", \"ID2\"])\n)\n```\n\n### Notifications\n\n```python\nnotifications = client.get_notifications()\nclient.drop_notifications(params=DropNotificationParams(...))\n```\n\n---\n\n## Fee Structure\n\n**IMPORTANT: Most Polymarket markets have ZERO fees (0% maker, 0% taker).**\n\n### 15-min Crypto Markets (Exception)\n\nOnly 15-minute BTC\u002FETH\u002FSOL\u002FXRP price prediction markets have fees:\n\n```\nfee = shares × 0.25 × (price × (1 - price))²\n```\n\n| Entry Price | Fee % (per side) |\n|-------------|------------------|\n| 0.50 | ~1.56% |\n| 0.60 or 0.40 | ~1.44% |\n| 0.70 or 0.30 | ~1.10% |\n| 0.80 or 0.20 | ~0.64% |\n| 0.90 or 0.10 | ~0.20% |\n\n**TAKER = crosses spread = PAYS fee**\n**MAKER = adds liquidity = NO fee + earns rebates**\n\nTo be a maker: Post orders that don't immediately fill (inside the spread).\n\n---\n\n## Decimal Precision Rules\n\n| Order Side | Price Decimals | Size Decimals |\n|------------|----------------|---------------|\n| BUY | 2 | 4 |\n| SELL | 2 | 2 |\n\n**Min order size:** $1 per side\n\n---\n\n## Complete Trading Example\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nProduction-ready Polymarket trading script\n\"\"\"\n\nimport os\nimport time\nimport requests\nfrom py_clob_client.client import ClobClient\nfrom py_clob_client.clob_types import OrderArgs, ApiCreds, OrderType\n\n# Initialize\nclient = ClobClient(\n    \"https:\u002F\u002Fclob.polymarket.com\",\n    key=os.getenv(\"PRIVATE_KEY\"),\n    chain_id=137,\n    funder=os.getenv(\"POLY_FUNDER_ADDRESS\"),\n    signature_type=2\n)\nclient.set_api_creds(ApiCreds(\n    api_key=os.getenv(\"POLY_API_KEY\"),\n    api_secret=os.getenv(\"POLY_API_SECRET\"),\n    api_passphrase=os.getenv(\"POLY_API_PASSPHRASE\")\n))\n\nTOKEN_ID = \"YOUR_TOKEN_ID\"\nWALLET = os.getenv(\"POLY_FUNDER_ADDRESS\")\nCTF = \"0x4D97DCd97eC945f40cF65F87097ACe5EA0476045\"\n\ndef get_balance(token_id):\n    \"\"\"Get position size\"\"\"\n    token_int = int(token_id)\n    data = f\"0x00fdd58e000000000000000000000000{WALLET[2:].lower()}{token_int:064x}\"\n    r = requests.post(\"https:\u002F\u002Fpolygon-rpc.com\u002F\", json={\n        \"jsonrpc\": \"2.0\", \"method\": \"eth_call\",\n        \"params\": [{\"to\": CTF, \"data\": data}, \"latest\"], \"id\": 1\n    })\n    return int(r.json().get(\"result\", \"0x0\"), 16) \u002F 1e6\n\ndef get_orderbook(token_id):\n    \"\"\"Get current bid\u002Fask\"\"\"\n    book = client.get_order_book(token_id)\n    return {\n        \"best_bid\": float(book.bids[0].price) if book.bids else 0,\n        \"best_ask\": float(book.asks[0].price) if book.asks else 1\n    }\n\n# Check position\nposition = get_balance(TOKEN_ID)\nprint(f\"Current position: {position} shares\")\n\n# Get market\nbook = get_orderbook(TOKEN_ID)\nprint(f\"Bid: {book['best_bid']:.2f}, Ask: {book['best_ask']:.2f}\")\n\n# Place a buy order (maker - inside spread)\nbuy_price = book['best_bid'] + 0.01  # 1 cent above bid\nif buy_price \u003C book['best_ask']:  # Ensure we're maker\n    result = client.create_and_post_order(OrderArgs(\n        token_id=TOKEN_ID,\n        price=buy_price,\n        size=10.0,\n        side=\"BUY\"\n    ))\n    print(f\"Buy order placed: {result}\")\n\n# Place a sell order (market sell via FOK)\nif position > 0:\n    result = client.create_and_post_order(OrderArgs(\n        token_id=TOKEN_ID,\n        price=0.01,  # Lowest price = immediate fill\n        size=position,\n        side=\"SELL\"\n    ))\n    print(f\"Sold position: {result}\")\n```\n\n---\n\n## Error Handling\n\n```python\nfrom py_clob_client.exceptions import PolyApiException\n\ntry:\n    result = client.create_and_post_order(OrderArgs(...))\nexcept PolyApiException as e:\n    print(f\"API Error: {e}\")\nexcept Exception as e:\n    print(f\"Error: {e}\")\n```\n\nCommon errors:\n- `\"insufficient balance\"` - Not enough USDC\u002Ftokens\n- `\"invalid price\"` - Price outside 0.01-0.99 or wrong decimals\n- `\"order too small\"` - Below minimum order size\n- `\"market closed\"` - Market not accepting orders\n\n---\n\n## CLI Commands (`\u002Fpoly`)\n\nAccess Polymarket trading directly from Claude Code:\n\n### Market Data\n```bash\n\u002Fpoly search \u003Cquery>                     # Search markets\n\u002Fpoly market \u003Ccondition-id>              # Market details\n\u002Fpoly book \u003Ctoken-id>                    # View orderbook\n```\n\n### Trading\n```bash\n\u002Fpoly buy \u003Ctoken-id> \u003Csize> \u003Cprice>      # Buy shares (limit)\n\u002Fpoly sell \u003Ctoken-id> \u003Csize> \u003Cprice>     # Sell shares (limit)\n\u002Fpoly orders                             # Open orders\n\u002Fpoly cancel \u003Corder-id>                  # Cancel order\n\u002Fpoly cancel all                         # Cancel all orders\n\u002Fpoly trades [limit]                     # Recent trade history\n\u002Fpoly balance                            # USDC + positions\n```\n\n### Advanced Orders\n```bash\n\u002Fpoly twap \u003Cbuy|sell> \u003Ctoken> \u003Ctotal> \u003Cprice> [slices] [interval-sec]\n\u002Fpoly bracket \u003Ctoken> \u003Csize> \u003Ctp> \u003Csl>   # TP + SL bracket\n\u002Fpoly trigger buy \u003Ctoken> \u003Csize> \u003Cprice> # Buy when price drops\n```\n\n**Note:** TWAP and bracket orders are persisted to the database and will automatically resume after restarts.\n\n### Auto-Redeem (Resolved Positions)\n```bash\n\u002Fpoly redeem                           # One-time redeem all resolved positions\n\u002Fpoly redeem start                     # Start auto-polling (default: every 60s)\n\u002Fpoly redeem stop                      # Stop auto-polling\n\u002Fpoly redeem status                    # Check auto-redeemer status\n\u002Fpoly redeem pending                   # List positions pending redemption\n\u002Fpoly redeem \u003CconditionId> \u003CtokenId>   # Redeem specific position\n```\n\n**Env vars:**\n- `POLY_REDEEM_INTERVAL_MS` - Polling interval in ms (default: 60000 = 1 minute)\n\n### Real-Time Fills (WebSocket)\n```bash\n\u002Fpoly fills                              # Connect fills WebSocket\n\u002Fpoly fills status                       # Show connection + recent fills\n\u002Fpoly fills stop                         # Disconnect fills WebSocket\n\u002Fpoly fills clear                        # Clear tracked fills\n```\n\n### Order Heartbeat\n```bash\n\u002Fpoly heartbeat                          # Start heartbeat (keeps orders alive)\n\u002Fpoly heartbeat status                   # Check heartbeat status\n\u002Fpoly heartbeat stop                     # Stop heartbeat (orders cancelled in 10s)\n```\n\n### Account & Settlements\n```bash\n\u002Fpoly settlements                        # View pending settlements from resolved markets\n\u002Fpoly allowance                          # Check USDC approval status\n\u002Fpoly orderbooks \u003Ctoken1> [token2] ...   # Batch fetch orderbooks\n```\n\n---\n\n## Complete ClobClient Method Reference\n\n### Health & Config (L0 - No Auth)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `get_ok()` | - | dict | Health check |\n| `get_server_time()` | - | dict | Server timestamp |\n| `get_address()` | - | str | Your signer address |\n| `get_collateral_address()` | - | str | USDC contract |\n| `get_conditional_address()` | - | str | CTF contract |\n| `get_exchange_address(neg_risk)` | bool | str | Exchange contract |\n\n### Market Data (L0 - No Auth)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `get_midpoint(token_id)` | str | dict | Mid price |\n| `get_midpoints(params)` | list[BookParams] | dict | Multiple mid prices |\n| `get_price(token_id, side)` | str, str | dict | Best price for side |\n| `get_prices(params)` | list[BookParams] | dict | Multiple prices |\n| `get_spread(token_id)` | str | dict | Bid-ask spread |\n| `get_spreads(params)` | list[BookParams] | dict | Multiple spreads |\n| `get_order_book(token_id)` | str | OrderBookSummary | Full orderbook |\n| `get_order_books(params)` | list[BookParams] | list | Multiple orderbooks |\n| `get_last_trade_price(token_id)` | str | dict | Last trade |\n| `get_last_trades_prices(params)` | list[BookParams] | dict | Multiple last trades |\n| `get_tick_size(token_id)` | str | TickSize | \"0.1\"\u002F\"0.01\"\u002F\"0.001\"\u002F\"0.0001\" |\n| `get_neg_risk(token_id)` | str | bool | Is neg_risk market |\n| `get_fee_rate_bps(token_id)` | str | int | Fee in basis points |\n\n### Market Discovery (L0 - No Auth)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `get_markets(next_cursor)` | str | dict | Paginated markets |\n| `get_simplified_markets(next_cursor)` | str | dict | Simplified markets |\n| `get_sampling_markets(next_cursor)` | str | dict | Featured markets |\n| `get_market(condition_id)` | str | dict | Single market |\n| `get_market_trades_events(condition_id)` | str | dict | Trade events |\n\n### Order Creation (L1 - Needs Private Key)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `create_order(order_args, options)` | OrderArgs, CreateOrderOptions | dict | Sign limit order |\n| `create_market_order(order_args, options)` | MarketOrderArgs, CreateOrderOptions | dict | Sign market order |\n| `calculate_market_price(token_id, side, amount, order_type)` | str, str, float, OrderType | float | Expected fill price |\n\n### Order Posting (L2 - Needs API Creds)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `post_order(order, orderType, post_only)` | SignedOrder, OrderType, bool | dict | Post single order |\n| `post_orders(args)` | list[PostOrdersArgs] | dict | Post batch orders |\n| `create_and_post_order(order_args, options)` | OrderArgs, PartialCreateOrderOptions | dict | Create + post (recommended) |\n\n### Order Cancellation (L2 - Needs API Creds)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `cancel(order_id)` | str | dict | Cancel one order |\n| `cancel_orders(order_ids)` | list[str] | dict | Cancel multiple |\n| `cancel_all()` | - | dict | Cancel ALL orders |\n| `cancel_market_orders(market, asset_id)` | str, str | dict | Cancel by market |\n\n### Order Queries (L2 - Needs API Creds)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `get_orders(params, next_cursor)` | OpenOrderParams, str | list | Get open orders |\n| `get_order(order_id)` | str | dict | Get specific order |\n| `get_trades(params, next_cursor)` | TradeParams, str | list | Trade history |\n\n### API Key Management (L2 - Needs API Creds)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `create_api_key(nonce)` | int | ApiCreds | Create new key |\n| `derive_api_key(nonce)` | int | ApiCreds | Derive existing key |\n| `create_or_derive_api_creds(nonce)` | int | ApiCreds | Create or derive |\n| `set_api_creds(creds)` | ApiCreds | - | Set credentials |\n| `get_api_keys()` | - | dict | List your keys |\n| `delete_api_key()` | - | dict | Delete current key |\n| `create_readonly_api_key()` | - | ReadonlyApiKeyResponse | Readonly key |\n| `get_readonly_api_keys()` | - | list[str] | List readonly keys |\n| `delete_readonly_api_key(key)` | str | bool | Delete readonly key |\n\n### Balance & Allowance (L2 - Needs API Creds)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `get_balance_allowance(params)` | BalanceAllowanceParams | dict | Check balance |\n| `update_balance_allowance(params)` | BalanceAllowanceParams | dict | Refresh allowance |\n\n### Advanced Features (L2 - Needs API Creds)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `post_heartbeat(heartbeat_id)` | str | dict | Keep orders alive (10s timeout) |\n| `is_order_scoring(params)` | OrderScoringParams | dict | Check if earning rewards |\n| `are_orders_scoring(params)` | OrdersScoringParams | dict | Check multiple orders |\n| `get_notifications()` | - | dict | Get notifications |\n| `drop_notifications(params)` | DropNotificationParams | dict | Delete notifications |\n| `get_closed_only_mode()` | - | dict | Check closed-only status |\n\n---\n\n## Contract Addresses (Polygon Mainnet)\n\n```python\nUSDC = \"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174\"           # Collateral token\nCTF  = \"0x4D97DCd97eC945f40cF65F87097ACe5EA0476045\"           # Conditional tokens (ERC-1155)\nEXCHANGE = \"0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E\"       # Regular exchange\nNEG_RISK = \"0xC5d563A36AE78145C45a50134d48A1215220f80a\"       # Neg risk exchange (crypto)\n```\n\n---\n\n## Quick Reference: Common Patterns\n\n### Check Position → Sell All\n```python\nbalance = get_token_balance(wallet, token_id)\nif balance > 0:\n    client.create_and_post_order(OrderArgs(\n        token_id=token_id, price=0.01, size=balance, side=\"SELL\"\n    ))\n```\n\n### Maker Entry (No Fees)\n```python\nbook = client.get_order_book(token_id)\nbest_bid = float(book.bids[0].price) if book.bids else 0\nmaker_price = best_bid + 0.01  # 1 cent above bid\nsigned = client.create_order(OrderArgs(token_id=token_id, price=maker_price, size=100, side=\"BUY\"))\nclient.post_order(signed, orderType=OrderType.GTC, post_only=True)\n```\n\n### Market Buy $50 Worth\n```python\nsigned = client.create_market_order(MarketOrderArgs(token_id=token_id, amount=50.0, side=\"BUY\"))\nclient.post_order(signed, orderType=OrderType.FOK)\n```\n\n### Cancel Everything\n```python\nclient.cancel_all()\n```\n\n---\n\n## WebSocket Channels (Real-Time Updates)\n\nPolymarket provides WebSocket channels for real-time updates. **No RPC needed - everything goes through CLOB.**\n\n### WebSocket URLs\n\n```python\nMARKET_WS = \"wss:\u002F\u002Fws-subscriptions-clob.polymarket.com\u002Fws\u002Fmarket\"\nUSER_WS = \"wss:\u002F\u002Fws-subscriptions-clob.polymarket.com\u002Fws\u002Fuser\"\n```\n\n### Market Channel (Public - No Auth)\n\nSubscribe to orderbook updates, price changes, trades for any market.\n\n```python\nimport websocket\nimport json\n\ndef on_message(ws, message):\n    data = json.loads(message)\n    event_type = data.get(\"event_type\")\n\n    if event_type == \"book\":\n        # Full orderbook snapshot (on subscribe + after trades)\n        print(f\"Book update: {data['bids']}, {data['asks']}\")\n\n    elif event_type == \"price_change\":\n        # Order placed\u002Fcancelled affecting price level\n        print(f\"Price change: {data}\")\n\n    elif event_type == \"last_trade_price\":\n        # Trade executed\n        print(f\"Trade: {data['price']} x {data['size']}\")\n\n    elif event_type == \"tick_size_change\":\n        # Tick size changed (price went extreme)\n        print(f\"Tick size: {data['old_tick_size']} -> {data['new_tick_size']}\")\n\ndef on_open(ws):\n    # Subscribe to specific token\n    ws.send(json.dumps({\n        \"type\": \"subscribe\",\n        \"channel\": \"market\",\n        \"assets_ids\": [TOKEN_ID]  # List of token IDs\n    }))\n\nws = websocket.WebSocketApp(\n    \"wss:\u002F\u002Fws-subscriptions-clob.polymarket.com\u002Fws\u002Fmarket\",\n    on_message=on_message,\n    on_open=on_open\n)\nws.run_forever()\n```\n\n### User Channel (Authenticated - For Fills)\n\nSubscribe to YOUR order updates, fills, trades. **This is how you get fill notifications.**\n\n```python\nimport websocket\nimport json\nimport hmac\nimport hashlib\nimport time\nimport base64\n\nAPI_KEY = os.getenv(\"POLY_API_KEY\")\nAPI_SECRET = os.getenv(\"POLY_API_SECRET\")\nAPI_PASSPHRASE = os.getenv(\"POLY_API_PASSPHRASE\")\n\ndef get_auth_headers():\n    \"\"\"Generate HMAC auth for WebSocket\"\"\"\n    timestamp = str(int(time.time()))\n    message = f\"GET\\n{timestamp}\\n\u002Fws\u002Fuser\"\n    signature = hmac.new(\n        base64.b64decode(API_SECRET),\n        message.encode(),\n        hashlib.sha256\n    ).digest()\n    return {\n        \"POLY-ADDRESS\": WALLET_ADDRESS,\n        \"POLY-SIGNATURE\": base64.b64encode(signature).decode(),\n        \"POLY-TIMESTAMP\": timestamp,\n        \"POLY-API-KEY\": API_KEY,\n        \"POLY-PASSPHRASE\": API_PASSPHRASE\n    }\n\ndef on_message(ws, message):\n    data = json.loads(message)\n    event_type = data.get(\"event_type\")\n\n    if event_type == \"trade\":\n        # YOUR FILL - order matched!\n        status = data.get(\"status\")  # MATCHED, MINED, CONFIRMED, FAILED\n        print(f\"FILL: {data['side']} {data['size']} @ {data['price']}\")\n        print(f\"  Status: {status}\")\n        print(f\"  Trade ID: {data['id']}\")\n        print(f\"  Market: {data['market']}\")\n\n        if status == \"CONFIRMED\":\n            print(\"  ✓ Trade confirmed on-chain!\")\n        elif status == \"FAILED\":\n            print(\"  ✗ Trade failed - check logs\")\n\n    elif event_type == \"order\":\n        order_type = data.get(\"type\")  # PLACEMENT, UPDATE, CANCELLATION\n        print(f\"ORDER {order_type}: {data['side']} {data['original_size']} @ {data['price']}\")\n        print(f\"  Filled: {data.get('size_matched', 0)}\")\n\n        if order_type == \"CANCELLATION\":\n            print(\"  Order cancelled\")\n\ndef on_open(ws):\n    # Subscribe with auth\n    ws.send(json.dumps({\n        \"type\": \"subscribe\",\n        \"channel\": \"user\",\n        \"auth\": get_auth_headers(),\n        # Optional: filter to specific market\n        # \"markets\": [CONDITION_ID]\n    }))\n\nws = websocket.WebSocketApp(\n    \"wss:\u002F\u002Fws-subscriptions-clob.polymarket.com\u002Fws\u002Fuser\",\n    on_message=on_message,\n    on_open=on_open\n)\nws.run_forever()\n```\n\n### Message Types Summary\n\n**Market Channel:**\n| Event | Trigger | Key Fields |\n|-------|---------|------------|\n| `book` | Subscribe, trades affect book | bids, asks, timestamp |\n| `price_change` | Order placed\u002Fcancelled | price, size, side |\n| `last_trade_price` | Trade executed | price, size, side |\n| `tick_size_change` | Price extreme (>0.96 or \u003C0.04) | old_tick_size, new_tick_size |\n\n**User Channel:**\n| Event | Trigger | Key Fields |\n|-------|---------|------------|\n| `trade` | Your order filled | status, side, size, price, market |\n| `order` | Order placed\u002Fupdated\u002Fcancelled | type (PLACEMENT\u002FUPDATE\u002FCANCELLATION), size_matched |\n\n### Trade Status Flow\n\n```\nMATCHED → MINED → CONFIRMED (success)\n                → RETRYING → CONFIRMED\u002FFAILED\n```\n\n### Keepalive\n\nSend PING every 10 seconds to keep connection alive:\n```python\nimport threading\n\ndef send_ping():\n    while True:\n        ws.send(json.dumps({\"type\": \"ping\"}))\n        time.sleep(10)\n\nthreading.Thread(target=send_ping, daemon=True).start()\n```\n\n### Real-Time Data Client (Alternative)\n\nPolymarket also provides `@polymarket\u002Freal-time-data-client` for TypeScript:\n\n```typescript\nimport { RealTimeDataClient } from \"@polymarket\u002Freal-time-data-client\";\n\nconst client = new RealTimeDataClient({\n    onMessage: (msg) => console.log(msg),\n    onConnect: (c) => {\n        \u002F\u002F Subscribe to user fills with auth\n        c.subscribe({\n            subscriptions: [{\n                topic: \"clob_user\",\n                type: \"*\",\n                clob_auth: {\n                    key: API_KEY,\n                    secret: API_SECRET,\n                    passphrase: API_PASSPHRASE\n                }\n            }]\n        });\n    }\n});\n\nclient.connect();\n```\n\n---\n\n## No RPC Needed - CLOB Handles Everything\n\n| Operation | Method |\n|-----------|--------|\n| Get positions | `GET \u002Fdata\u002Fpositions?user={address}` via Gamma API |\n| Get balance | `client.get_balance_allowance()` |\n| Place orders | `client.create_and_post_order()` |\n| Get fills | User WebSocket channel |\n| Get prices | `client.get_order_book()` or Market WebSocket |\n| Cancel orders | `client.cancel()` |\n\nThe only time you might use RPC is to check on-chain token balances independently, but even that's available via Gamma API positions endpoint.\n","# Polymarket Trading - Complete API Reference\n\nFull access to Polymarket's CLOB (Central Limit Order Book) via the official `py_clob_client` library.\n\n**60+ methods documented. This is the complete reference.**\n\n## Required Environment Variables\n\n```bash\nPRIVATE_KEY=0x...           # Ethereum private key for signing\nPOLY_FUNDER_ADDRESS=0x...   # Your wallet address on Polygon\nPOLY_API_KEY=...            # From Polymarket API\nPOLY_API_SECRET=...         # Base64 encoded secret\nPOLY_API_PASSPHRASE=...     # API passphrase\n```\n\n## Installation\n\n```bash\npip install py-clob-client requests\n```\n\n---\n\n## Authentication Levels\n\n| Level | Requirements | Capabilities |\n|-------|--------------|--------------|\n| **L0** | None | Read-only: orderbooks, prices, markets |\n| **L1** | Private key | Create & sign orders (not post) |\n| **L2** | Private key + API creds | Full trading: post orders, cancel, query |\n\n### Signature Types\n\n| Type | Use Case |\n|------|----------|\n| `0` | Standard EOA (MetaMask, hardware wallets) |\n| `1` | Magic\u002Femail wallets (delegated signing) |\n| `2` | Proxy wallets (Gnosis Safe, browser proxy) |\n\n---\n\n## ClobClient - Complete API (60+ Methods)\n\n### Initialization\n\n```python\nfrom py_clob_client.client import ClobClient\nfrom py_clob_client.clob_types import (\n    OrderArgs, MarketOrderArgs, ApiCreds, OrderType,\n    BookParams, TradeParams, OpenOrderParams, BalanceAllowanceParams,\n    AssetType, OrderScoringParams, OrdersScoringParams, DropNotificationParams\n)\nfrom py_clob_client.order_builder.constants import BUY, SELL\nfrom py_clob_client.constants import POLYGON  # 137\n\n# Level 2 Auth (full trading access)\nclient = ClobClient(\n    host=\"https:\u002F\u002Fclob.polymarket.com\",\n    key=os.getenv(\"PRIVATE_KEY\"),           # Private key for signing\n    chain_id=POLYGON,                        # 137 for mainnet, 80002 for Amoy testnet\n    funder=os.getenv(\"POLY_FUNDER_ADDRESS\"), # Wallet address (for proxy wallets)\n    signature_type=2                         # 0=EOA, 1=MagicLink, 2=Proxy\n)\n\n# Set API credentials for authenticated endpoints\nclient.set_api_creds(ApiCreds(\n    api_key=os.getenv(\"POLY_API_KEY\"),\n    api_secret=os.getenv(\"POLY_API_SECRET\"),\n    api_passphrase=os.getenv(\"POLY_API_PASSPHRASE\")\n))\n```\n\n### Health & Configuration\n\n```python\nclient.get_ok()                    # Check if server is up\nclient.get_server_time()           # Get server timestamp\nclient.get_address()               # Your signer's public address\nclient.get_collateral_address()    # USDC contract address\nclient.get_conditional_address()   # CTF contract address\nclient.get_exchange_address()      # Exchange contract (neg_risk=False default)\n```\n\n### Market Data - Single Token\n\n```python\n# Get prices and spreads\nclient.get_midpoint(token_id)              # Mid market price\nclient.get_price(token_id, side=\"BUY\")     # Best price for side\nclient.get_spread(token_id)                # Current spread\nclient.get_last_trade_price(token_id)      # Last executed trade price\n\n# Get full orderbook\norderbook = client.get_order_book(token_id)\n# Returns: OrderBookSummary with bids, asks, tick_size, neg_risk, timestamp, hash\n```\n\n### Market Data - Batch (Multiple Tokens)\n\n```python\nparams = [\n    BookParams(token_id=\"TOKEN1\", side=\"BUY\"),\n    BookParams(token_id=\"TOKEN2\", side=\"SELL\")\n]\n\nclient.get_midpoints(params)           # Multiple midpoints\nclient.get_prices(params)              # Multiple prices\nclient.get_spreads(params)             # Multiple spreads\nclient.get_order_books(params)         # Multiple orderbooks\nclient.get_last_trades_prices(params)  # Multiple last prices\n```\n\n### Market Metadata\n\n```python\nclient.get_tick_size(token_id)      # Returns: \"0.1\", \"0.01\", \"0.001\", or \"0.0001\"\nclient.get_neg_risk(token_id)       # Returns: True\u002FFalse (negative risk market)\nclient.get_fee_rate_bps(token_id)   # Returns: fee rate in basis points (0 or 1000)\n```\n\n---\n\n## Order Types\n\n```python\nfrom py_clob_client.clob_types import OrderType\n\nOrderType.GTC   # Good Till Cancelled - stays open until filled\u002Fcancelled\nOrderType.FOK   # Fill Or Kill - fill entirely immediately or cancel\nOrderType.GTD   # Good Till Date - expires at timestamp (min 60 seconds)\nOrderType.FAK   # Fill And Kill - fill what's possible, cancel rest\n```\n\n### When to Use Each Order Type\n\n| Type | Use Case | Example |\n|------|----------|---------|\n| **GTC** | Entries - wait for fill | Place buy at 0.45, wait for dip |\n| **FOK** | Exits - need immediate fill | Market sell entire position NOW |\n| **GTD** | Time-limited orders | Offer expires in 5 minutes |\n| **FAK** | Partial fills OK | Get as much as possible now |\n\n### OrderArgs - Limit Orders\n\n```python\nOrderArgs(\n    token_id: str,           # Token ID (outcome to trade)\n    price: float,            # Price 0.01-0.99\n    size: float,             # Number of shares\n    side: str,               # \"BUY\" or \"SELL\" (or use BUY\u002FSELL constants)\n    fee_rate_bps: int = 0,   # Optional: fee rate in bps (0 or check market)\n    nonce: int = 0,          # Optional: unique nonce for cancellation\n    expiration: int = 0,     # Optional: expiry timestamp (0 = GTC, use timestamp for GTD)\n    taker: str = ZERO_ADDRESS  # Optional: specific taker (ZERO_ADDRESS = anyone)\n)\n```\n\n### MarketOrderArgs - Market Orders\n\n```python\nMarketOrderArgs(\n    token_id: str,           # Token ID\n    amount: float,           # Total USDC amount to spend (BUY) or shares (SELL)\n    side: str,               # \"BUY\" or \"SELL\"\n    price: float = 0,        # Optional: worst acceptable price (slippage protection)\n    fee_rate_bps: int = 0,   # Optional: fee rate\n    nonce: int = 0,          # Optional: nonce\n    taker: str = ZERO_ADDRESS,  # Optional: taker address\n    order_type: OrderType = FOK  # Optional: FOK (default) or FAK\n)\n```\n\n### Complete Order Examples\n\n```python\nfrom py_clob_client.order_builder.constants import BUY, SELL\n\n# 1. LIMIT BUY (GTC) - sits on book until filled\norder = client.create_and_post_order(\n    OrderArgs(token_id=TOKEN_ID, price=0.45, size=100.0, side=BUY)\n)\n\n# 2. LIMIT SELL (GTC)\norder = client.create_and_post_order(\n    OrderArgs(token_id=TOKEN_ID, price=0.55, size=50.0, side=SELL)\n)\n\n# 3. MARKET BUY - spend $100 USDC at current prices (FOK)\nsigned = client.create_market_order(\n    MarketOrderArgs(token_id=TOKEN_ID, amount=100.0, side=BUY)\n)\nresult = client.post_order(signed, orderType=OrderType.FOK)\n\n# 4. MARKET SELL - sell all shares immediately (FOK)\nsigned = client.create_market_order(\n    MarketOrderArgs(token_id=TOKEN_ID, amount=my_shares, side=SELL)\n)\nresult = client.post_order(signed, orderType=OrderType.FOK)\n\n# 5. POST-ONLY MAKER ORDER (avoid taker fees, earn rebates)\nsigned = client.create_order(\n    OrderArgs(token_id=TOKEN_ID, price=0.44, size=100.0, side=BUY)\n)\nresult = client.post_order(signed, orderType=OrderType.GTC, post_only=True)\n# If order would cross spread, it gets REJECTED instead of taking\n\n# 6. GOOD TIL DATE (GTD) - expires after timestamp\nimport time\nexpiry = int(time.time()) + 300  # 5 minutes from now\nsigned = client.create_order(\n    OrderArgs(token_id=TOKEN_ID, price=0.50, size=100.0, side=BUY, expiration=expiry)\n)\nresult = client.post_order(signed, orderType=OrderType.GTD)\n\n# 7. FILL AND KILL (FAK) - fill what you can, cancel rest\nsigned = client.create_market_order(\n    MarketOrderArgs(token_id=TOKEN_ID, amount=1000.0, side=BUY)\n)\nresult = client.post_order(signed, orderType=OrderType.FAK)\n```\n\n---\n\n## Order Operations\n\n### Create and Post Orders\n\n```python\n# SIMPLE: Create and post in one call (recommended)\nresult = client.create_and_post_order(\n    OrderArgs(\n        token_id=\"123456789012345678901234567890\",\n        price=0.45,\n        size=10.0,\n        side=\"BUY\"\n    )\n)\n# Returns: {\"orderID\": \"...\", \"status\": \"...\", ...}\n\n# ADVANCED: Separate create and post\norder = client.create_order(OrderArgs(...))  # Returns SignedOrder\nresult = client.post_order(order, orderType=OrderType.GTC, post_only=False)\n\n# Market order (calculates price automatically)\nresult = client.create_market_order(\n    MarketOrderArgs(\n        token_id=\"...\",\n        amount=100.0,    # Spend $100 USDC\n        side=\"BUY\"\n    )\n)\n\n# Calculate expected fill price before market order\nprice = client.calculate_market_price(\n    token_id=\"...\",\n    side=\"BUY\",\n    amount=100.0,\n    order_type=OrderType.FOK\n)\n```\n\n### Cancel Orders\n\n```python\nclient.cancel(order_id=\"ORDER_ID\")           # Cancel specific order\nclient.cancel_orders([\"ID1\", \"ID2\", \"ID3\"])  # Cancel multiple\nclient.cancel_all()                          # Cancel ALL open orders\nclient.cancel_market_orders(                 # Cancel by market\u002Fasset\n    market=\"CONDITION_ID\",\n    asset_id=\"TOKEN_ID\"\n)\n```\n\n### Query Orders\n\n```python\n# Get all open orders\norders = client.get_orders(\n    params=OpenOrderParams(\n        id=\"ORDER_ID\",      # Optional: specific order\n        market=\"COND_ID\",   # Optional: filter by market\n        asset_id=\"TOKEN\"    # Optional: filter by token\n    ),\n    next_cursor=\"MA==\"      # For pagination\n)\n\n# Get specific order\norder = client.get_order(order_id=\"ORDER_ID\")\n```\n\n### Trade History\n\n```python\ntrades = client.get_trades(\n    params=TradeParams(\n        id=\"TRADE_ID\",           # Optional: specific trade\n        maker_address=\"0x...\",   # Optional: filter by maker\n        market=\"CONDITION_ID\",   # Optional: filter by market\n        asset_id=\"TOKEN_ID\",     # Optional: filter by token\n        before=\"2024-01-01\",     # Optional: before date\n        after=\"2023-01-01\"       # Optional: after date\n    ),\n    next_cursor=\"MA==\"\n)\n```\n\n### Balance & Allowance\n\n```python\n# Check balance and allowances\nbalance = client.get_balance_allowance(\n    params=BalanceAllowanceParams(\n        asset_type=AssetType.COLLATERAL,  # USDC balance\n        # or AssetType.CONDITIONAL         # Token balance\n        token_id=\"TOKEN_ID\"                # For conditional tokens\n    )\n)\n\n# Update\u002Frefresh allowance cache\nclient.update_balance_allowance(params=...)\n```\n\n---\n\n## Market Discovery\n\n### Get Markets from CLOB\n\n```python\n# All active markets\nmarkets = client.get_markets(next_cursor=\"MA==\")\nsimplified = client.get_simplified_markets()\n\n# Specific market\nmarket = client.get_market(condition_id=\"CONDITION_ID\")\n\n# Market trade events\nevents = client.get_market_trades_events(condition_id=\"CONDITION_ID\")\n\n# Sampling\u002Ffeatured markets\nclient.get_sampling_markets()\nclient.get_sampling_simplified_markets()\n```\n\n### Get Markets from Gamma API (More Details)\n\n```python\nimport requests\n\ndef search_markets(query: str, limit: int = 10):\n    \"\"\"Search Polymarket markets by keyword\"\"\"\n    url = \"https:\u002F\u002Fgamma-api.polymarket.com\u002Fmarkets\"\n    params = {\n        \"_q\": query,\n        \"active\": \"true\",\n        \"closed\": \"false\",\n        \"_limit\": limit\n    }\n    r = requests.get(url, params=params)\n    return r.json()\n\n# Get market details\nmarkets = search_markets(\"bitcoin\")\nfor m in markets:\n    print(f\"Question: {m['question']}\")\n    print(f\"Condition ID: {m['condition_id']}\")\n    print(f\"Volume: ${m.get('volume', 0):,.2f}\")\n    for token in m.get('tokens', []):\n        print(f\"  {token['outcome']}: {token['token_id']}\")\n        print(f\"    Price: {float(token['price']):.2f}\")\n```\n\n---\n\n## On-Chain Operations\n\n### Check Token Balance (Position Size)\n\n```python\nimport requests\n\nCTF_CONTRACT = \"0x4D97DCd97eC945f40cF65F87097ACe5EA0476045\"\nRPC_URL = \"https:\u002F\u002Fpolygon-rpc.com\u002F\"\n\ndef get_token_balance(wallet: str, token_id: str) -> float:\n    \"\"\"Get balance of a specific outcome token in shares\"\"\"\n    token_int = int(token_id)\n    # ERC-1155 balanceOf(address,uint256)\n    data = f\"0x00fdd58e000000000000000000000000{wallet[2:].lower()}{token_int:064x}\"\n\n    r = requests.post(RPC_URL, json={\n        \"jsonrpc\": \"2.0\",\n        \"method\": \"eth_call\",\n        \"params\": [{\"to\": CTF_CONTRACT, \"data\": data}, \"latest\"],\n        \"id\": 1\n    })\n\n    result = r.json().get(\"result\", \"0x0\")\n    balance = int(result, 16) \u002F 1e6  # Convert from raw to shares\n    return balance\n\n# Usage\nbalance = get_token_balance(\n    wallet=\"0x7c2211103e7Fbb257Ac6fa59f972cfd8bc9D4795\",\n    token_id=\"12345678901234567890\"\n)\nprint(f\"Position: {balance} shares\")\n```\n\n### Check USDC Balance\n\n```python\nUSDC_CONTRACT = \"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174\"\n\ndef get_usdc_balance(wallet: str) -> float:\n    \"\"\"Get USDC balance on Polygon\"\"\"\n    # ERC-20 balanceOf(address)\n    data = f\"0x70a08231000000000000000000000000{wallet[2:].lower()}\"\n\n    r = requests.post(RPC_URL, json={\n        \"jsonrpc\": \"2.0\",\n        \"method\": \"eth_call\",\n        \"params\": [{\"to\": USDC_CONTRACT, \"data\": data}, \"latest\"],\n        \"id\": 1\n    })\n\n    result = r.json().get(\"result\", \"0x0\")\n    return int(result, 16) \u002F 1e6  # USDC has 6 decimals\n```\n\n---\n\n## API Key Management\n\n```python\n# Create new API key\ncreds = client.create_api_key(nonce=0)\n\n# Derive existing API key (if you lost creds but have private key)\ncreds = client.derive_api_key(nonce=0)\n\n# Create or derive (tries both)\ncreds = client.create_or_derive_api_creds(nonce=0)\n\n# Get all your API keys\nkeys = client.get_api_keys()\n\n# Delete current API key\nclient.delete_api_key()\n\n# Readonly API keys (for monitoring only)\nreadonly = client.create_readonly_api_key()\nclient.get_readonly_api_keys()\nclient.delete_readonly_api_key(key=\"...\")\nclient.validate_readonly_api_key(address=\"0x...\", key=\"...\")\n```\n\n---\n\n## Advanced Features\n\n### Order Heartbeat (Keep Orders Alive)\n\n```python\n# Start heartbeat - if not sent within 10s, all orders cancelled\nheartbeat_id = client.post_heartbeat(heartbeat_id=None)\n\n# Continue sending heartbeats\nwhile trading:\n    client.post_heartbeat(heartbeat_id=heartbeat_id)\n    time.sleep(5)\n```\n\n### Order Scoring\n\n```python\n# Check if order is scoring (earning rewards)\nis_scoring = client.is_order_scoring(\n    params=OrderScoringParams(order_id=\"...\")\n)\n\n# Check multiple orders\nscores = client.are_orders_scoring(\n    params=OrdersScoringParams(order_ids=[\"ID1\", \"ID2\"])\n)\n```\n\n### Notifications\n\n```python\nnotifications = client.get_notifications()\nclient.drop_notifications(params=DropNotificationParams(...))\n```\n\n---\n\n## Fee Structure\n\n**IMPORTANT: Most Polymarket markets have ZERO fees (0% maker, 0% taker).**\n\n### 15-min Crypto Markets (Exception)\n\nOnly 15-minute BTC\u002FETH\u002FSOL\u002FXRP price prediction markets have fees:\n\n```\nfee = shares × 0.25 × (price × (1 - price))²\n```\n\n| Entry Price | Fee % (per side) |\n|-------------|------------------|\n| 0.50 | ~1.56% |\n| 0.60 or 0.40 | ~1.44% |\n| 0.70 or 0.30 | ~1.10% |\n| 0.80 or 0.20 | ~0.64% |\n| 0.90 or 0.10 | ~0.20% |\n\n**TAKER = crosses spread = PAYS fee**\n**MAKER = adds liquidity = NO fee + earns rebates**\n\nTo be a maker: Post orders that don't immediately fill (inside the spread).\n\n---\n\n## Decimal Precision Rules\n\n| Order Side | Price Decimals | Size Decimals |\n|------------|----------------|---------------|\n| BUY | 2 | 4 |\n| SELL | 2 | 2 |\n\n**Min order size:** $1 per side\n\n---\n\n## Complete Trading Example\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nProduction-ready Polymarket trading script\n\"\"\"\n\nimport os\nimport time\nimport requests\nfrom py_clob_client.client import ClobClient\nfrom py_clob_client.clob_types import OrderArgs, ApiCreds, OrderType\n\n# Initialize\nclient = ClobClient(\n    \"https:\u002F\u002Fclob.polymarket.com\",\n    key=os.getenv(\"PRIVATE_KEY\"),\n    chain_id=137,\n    funder=os.getenv(\"POLY_FUNDER_ADDRESS\"),\n    signature_type=2\n)\nclient.set_api_creds(ApiCreds(\n    api_key=os.getenv(\"POLY_API_KEY\"),\n    api_secret=os.getenv(\"POLY_API_SECRET\"),\n    api_passphrase=os.getenv(\"POLY_API_PASSPHRASE\")\n))\n\nTOKEN_ID = \"YOUR_TOKEN_ID\"\nWALLET = os.getenv(\"POLY_FUNDER_ADDRESS\")\nCTF = \"0x4D97DCd97eC945f40cF65F87097ACe5EA0476045\"\n\ndef get_balance(token_id):\n    \"\"\"Get position size\"\"\"\n    token_int = int(token_id)\n    data = f\"0x00fdd58e000000000000000000000000{WALLET[2:].lower()}{token_int:064x}\"\n    r = requests.post(\"https:\u002F\u002Fpolygon-rpc.com\u002F\", json={\n        \"jsonrpc\": \"2.0\", \"method\": \"eth_call\",\n        \"params\": [{\"to\": CTF, \"data\": data}, \"latest\"], \"id\": 1\n    })\n    return int(r.json().get(\"result\", \"0x0\"), 16) \u002F 1e6\n\ndef get_orderbook(token_id):\n    \"\"\"Get current bid\u002Fask\"\"\"\n    book = client.get_order_book(token_id)\n    return {\n        \"best_bid\": float(book.bids[0].price) if book.bids else 0,\n        \"best_ask\": float(book.asks[0].price) if book.asks else 1\n    }\n\n# Check position\nposition = get_balance(TOKEN_ID)\nprint(f\"Current position: {position} shares\")\n\n# Get market\nbook = get_orderbook(TOKEN_ID)\nprint(f\"Bid: {book['best_bid']:.2f}, Ask: {book['best_ask']:.2f}\")\n\n# Place a buy order (maker - inside spread)\nbuy_price = book['best_bid'] + 0.01  # 1 cent above bid\nif buy_price \u003C book['best_ask']:  # Ensure we're maker\n    result = client.create_and_post_order(OrderArgs(\n        token_id=TOKEN_ID,\n        price=buy_price,\n        size=10.0,\n        side=\"BUY\"\n    ))\n    print(f\"Buy order placed: {result}\")\n\n# Place a sell order (market sell via FOK)\nif position > 0:\n    result = client.create_and_post_order(OrderArgs(\n        token_id=TOKEN_ID,\n        price=0.01,  # Lowest price = immediate fill\n        size=position,\n        side=\"SELL\"\n    ))\n    print(f\"Sold position: {result}\")\n```\n\n---\n\n## Error Handling\n\n```python\nfrom py_clob_client.exceptions import PolyApiException\n\ntry:\n    result = client.create_and_post_order(OrderArgs(...))\nexcept PolyApiException as e:\n    print(f\"API Error: {e}\")\nexcept Exception as e:\n    print(f\"Error: {e}\")\n```\n\nCommon errors:\n- `\"insufficient balance\"` - Not enough USDC\u002Ftokens\n- `\"invalid price\"` - Price outside 0.01-0.99 or wrong decimals\n- `\"order too small\"` - Below minimum order size\n- `\"market closed\"` - Market not accepting orders\n\n---\n\n## CLI Commands (`\u002Fpoly`)\n\nAccess Polymarket trading directly from Claude Code:\n\n### Market Data\n```bash\n\u002Fpoly search \u003Cquery>                     # Search markets\n\u002Fpoly market \u003Ccondition-id>              # Market details\n\u002Fpoly book \u003Ctoken-id>                    # View orderbook\n```\n\n### Trading\n```bash\n\u002Fpoly buy \u003Ctoken-id> \u003Csize> \u003Cprice>      # Buy shares (limit)\n\u002Fpoly sell \u003Ctoken-id> \u003Csize> \u003Cprice>     # Sell shares (limit)\n\u002Fpoly orders                             # Open orders\n\u002Fpoly cancel \u003Corder-id>                  # Cancel order\n\u002Fpoly cancel all                         # Cancel all orders\n\u002Fpoly trades [limit]                     # Recent trade history\n\u002Fpoly balance                            # USDC + positions\n```\n\n### Advanced Orders\n```bash\n\u002Fpoly twap \u003Cbuy|sell> \u003Ctoken> \u003Ctotal> \u003Cprice> [slices] [interval-sec]\n\u002Fpoly bracket \u003Ctoken> \u003Csize> \u003Ctp> \u003Csl>   # TP + SL bracket\n\u002Fpoly trigger buy \u003Ctoken> \u003Csize> \u003Cprice> # Buy when price drops\n```\n\n**Note:** TWAP and bracket orders are persisted to the database and will automatically resume after restarts.\n\n### Auto-Redeem (Resolved Positions)\n```bash\n\u002Fpoly redeem                           # One-time redeem all resolved positions\n\u002Fpoly redeem start                     # Start auto-polling (default: every 60s)\n\u002Fpoly redeem stop                      # Stop auto-polling\n\u002Fpoly redeem status                    # Check auto-redeemer status\n\u002Fpoly redeem pending                   # List positions pending redemption\n\u002Fpoly redeem \u003CconditionId> \u003CtokenId>   # Redeem specific position\n```\n\n**Env vars:**\n- `POLY_REDEEM_INTERVAL_MS` - Polling interval in ms (default: 60000 = 1 minute)\n\n### Real-Time Fills (WebSocket)\n```bash\n\u002Fpoly fills                              # Connect fills WebSocket\n\u002Fpoly fills status                       # Show connection + recent fills\n\u002Fpoly fills stop                         # Disconnect fills WebSocket\n\u002Fpoly fills clear                        # Clear tracked fills\n```\n\n### Order Heartbeat\n```bash\n\u002Fpoly heartbeat                          # Start heartbeat (keeps orders alive)\n\u002Fpoly heartbeat status                   # Check heartbeat status\n\u002Fpoly heartbeat stop                     # Stop heartbeat (orders cancelled in 10s)\n```\n\n### Account & Settlements\n```bash\n\u002Fpoly settlements                        # View pending settlements from resolved markets\n\u002Fpoly allowance                          # Check USDC approval status\n\u002Fpoly orderbooks \u003Ctoken1> [token2] ...   # Batch fetch orderbooks\n```\n\n---\n\n## Complete ClobClient Method Reference\n\n### Health & Config (L0 - No Auth)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `get_ok()` | - | dict | Health check |\n| `get_server_time()` | - | dict | Server timestamp |\n| `get_address()` | - | str | Your signer address |\n| `get_collateral_address()` | - | str | USDC contract |\n| `get_conditional_address()` | - | str | CTF contract |\n| `get_exchange_address(neg_risk)` | bool | str | Exchange contract |\n\n### Market Data (L0 - No Auth)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `get_midpoint(token_id)` | str | dict | Mid price |\n| `get_midpoints(params)` | list[BookParams] | dict | Multiple mid prices |\n| `get_price(token_id, side)` | str, str | dict | Best price for side |\n| `get_prices(params)` | list[BookParams] | dict | Multiple prices |\n| `get_spread(token_id)` | str | dict | Bid-ask spread |\n| `get_spreads(params)` | list[BookParams] | dict | Multiple spreads |\n| `get_order_book(token_id)` | str | OrderBookSummary | Full orderbook |\n| `get_order_books(params)` | list[BookParams] | list | Multiple orderbooks |\n| `get_last_trade_price(token_id)` | str | dict | Last trade |\n| `get_last_trades_prices(params)` | list[BookParams] | dict | Multiple last trades |\n| `get_tick_size(token_id)` | str | TickSize | \"0.1\"\u002F\"0.01\"\u002F\"0.001\"\u002F\"0.0001\" |\n| `get_neg_risk(token_id)` | str | bool | Is neg_risk market |\n| `get_fee_rate_bps(token_id)` | str | int | Fee in basis points |\n\n### Market Discovery (L0 - No Auth)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `get_markets(next_cursor)` | str | dict | Paginated markets |\n| `get_simplified_markets(next_cursor)` | str | dict | Simplified markets |\n| `get_sampling_markets(next_cursor)` | str | dict | Featured markets |\n| `get_market(condition_id)` | str | dict | Single market |\n| `get_market_trades_events(condition_id)` | str | dict | Trade events |\n\n### Order Creation (L1 - Needs Private Key)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `create_order(order_args, options)` | OrderArgs, CreateOrderOptions | dict | Sign limit order |\n| `create_market_order(order_args, options)` | MarketOrderArgs, CreateOrderOptions | dict | Sign market order |\n| `calculate_market_price(token_id, side, amount, order_type)` | str, str, float, OrderType | float | Expected fill price |\n\n### Order Posting (L2 - Needs API Creds)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `post_order(order, orderType, post_only)` | SignedOrder, OrderType, bool | dict | Post single order |\n| `post_orders(args)` | list[PostOrdersArgs] | dict | Post batch orders |\n| `create_and_post_order(order_args, options)` | OrderArgs, PartialCreateOrderOptions | dict | Create + post (recommended) |\n\n### Order Cancellation (L2 - Needs API Creds)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `cancel(order_id)` | str | dict | Cancel one order |\n| `cancel_orders(order_ids)` | list[str] | dict | Cancel multiple |\n| `cancel_all()` | - | dict | Cancel ALL orders |\n| `cancel_market_orders(market, asset_id)` | str, str | dict | Cancel by market |\n\n### Order Queries (L2 - Needs API Creds)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `get_orders(params, next_cursor)` | OpenOrderParams, str | list | Get open orders |\n| `get_order(order_id)` | str | dict | Get specific order |\n| `get_trades(params, next_cursor)` | TradeParams, str | list | Trade history |\n\n### API Key Management (L2 - Needs API Creds)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `create_api_key(nonce)` | int | ApiCreds | Create new key |\n| `derive_api_key(nonce)` | int | ApiCreds | Derive existing key |\n| `create_or_derive_api_creds(nonce)` | int | ApiCreds | Create or derive |\n| `set_api_creds(creds)` | ApiCreds | - | Set credentials |\n| `get_api_keys()` | - | dict | List your keys |\n| `delete_api_key()` | - | dict | Delete current key |\n| `create_readonly_api_key()` | - | ReadonlyApiKeyResponse | Readonly key |\n| `get_readonly_api_keys()` | - | list[str] | List readonly keys |\n| `delete_readonly_api_key(key)` | str | bool | Delete readonly key |\n\n### Balance & Allowance (L2 - Needs API Creds)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `get_balance_allowance(params)` | BalanceAllowanceParams | dict | Check balance |\n| `update_balance_allowance(params)` | BalanceAllowanceParams | dict | Refresh allowance |\n\n### Advanced Features (L2 - Needs API Creds)\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `post_heartbeat(heartbeat_id)` | str | dict | Keep orders alive (10s timeout) |\n| `is_order_scoring(params)` | OrderScoringParams | dict | Check if earning rewards |\n| `are_orders_scoring(params)` | OrdersScoringParams | dict | Check multiple orders |\n| `get_notifications()` | - | dict | Get notifications |\n| `drop_notifications(params)` | DropNotificationParams | dict | Delete notifications |\n| `get_closed_only_mode()` | - | dict | Check closed-only status |\n\n---\n\n## Contract Addresses (Polygon Mainnet)\n\n```python\nUSDC = \"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174\"           # Collateral token\nCTF  = \"0x4D97DCd97eC945f40cF65F87097ACe5EA0476045\"           # Conditional tokens (ERC-1155)\nEXCHANGE = \"0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E\"       # Regular exchange\nNEG_RISK = \"0xC5d563A36AE78145C45a50134d48A1215220f80a\"       # Neg risk exchange (crypto)\n```\n\n---\n\n## Quick Reference: Common Patterns\n\n### Check Position → Sell All\n```python\nbalance = get_token_balance(wallet, token_id)\nif balance > 0:\n    client.create_and_post_order(OrderArgs(\n        token_id=token_id, price=0.01, size=balance, side=\"SELL\"\n    ))\n```\n\n### Maker Entry (No Fees)\n```python\nbook = client.get_order_book(token_id)\nbest_bid = float(book.bids[0].price) if book.bids else 0\nmaker_price = best_bid + 0.01  # 1 cent above bid\nsigned = client.create_order(OrderArgs(token_id=token_id, price=maker_price, size=100, side=\"BUY\"))\nclient.post_order(signed, orderType=OrderType.GTC, post_only=True)\n```\n\n### Market Buy $50 Worth\n```python\nsigned = client.create_market_order(MarketOrderArgs(token_id=token_id, amount=50.0, side=\"BUY\"))\nclient.post_order(signed, orderType=OrderType.FOK)\n```\n\n### Cancel Everything\n```python\nclient.cancel_all()\n```\n\n---\n\n## WebSocket Channels (Real-Time Updates)\n\nPolymarket provides WebSocket channels for real-time updates. **No RPC needed - everything goes through CLOB.**\n\n### WebSocket URLs\n\n```python\nMARKET_WS = \"wss:\u002F\u002Fws-subscriptions-clob.polymarket.com\u002Fws\u002Fmarket\"\nUSER_WS = \"wss:\u002F\u002Fws-subscriptions-clob.polymarket.com\u002Fws\u002Fuser\"\n```\n\n### Market Channel (Public - No Auth)\n\nSubscribe to orderbook updates, price changes, trades for any market.\n\n```python\nimport websocket\nimport json\n\ndef on_message(ws, message):\n    data = json.loads(message)\n    event_type = data.get(\"event_type\")\n\n    if event_type == \"book\":\n        # Full orderbook snapshot (on subscribe + after trades)\n        print(f\"Book update: {data['bids']}, {data['asks']}\")\n\n    elif event_type == \"price_change\":\n        # Order placed\u002Fcancelled affecting price level\n        print(f\"Price change: {data}\")\n\n    elif event_type == \"last_trade_price\":\n        # Trade executed\n        print(f\"Trade: {data['price']} x {data['size']}\")\n\n    elif event_type == \"tick_size_change\":\n        # Tick size changed (price went extreme)\n        print(f\"Tick size: {data['old_tick_size']} -> {data['new_tick_size']}\")\n\ndef on_open(ws):\n    # Subscribe to specific token\n    ws.send(json.dumps({\n        \"type\": \"subscribe\",\n        \"channel\": \"market\",\n        \"assets_ids\": [TOKEN_ID]  # List of token IDs\n    }))\n\nws = websocket.WebSocketApp(\n    \"wss:\u002F\u002Fws-subscriptions-clob.polymarket.com\u002Fws\u002Fmarket\",\n    on_message=on_message,\n    on_open=on_open\n)\nws.run_forever()\n```\n\n### User Channel (Authenticated - For Fills)\n\nSubscribe to YOUR order updates, fills, trades. **This is how you get fill notifications.**\n\n```python\nimport websocket\nimport json\nimport hmac\nimport hashlib\nimport time\nimport base64\n\nAPI_KEY = os.getenv(\"POLY_API_KEY\")\nAPI_SECRET = os.getenv(\"POLY_API_SECRET\")\nAPI_PASSPHRASE = os.getenv(\"POLY_API_PASSPHRASE\")\n\ndef get_auth_headers():\n    \"\"\"Generate HMAC auth for WebSocket\"\"\"\n    timestamp = str(int(time.time()))\n    message = f\"GET\\n{timestamp}\\n\u002Fws\u002Fuser\"\n    signature = hmac.new(\n        base64.b64decode(API_SECRET),\n        message.encode(),\n        hashlib.sha256\n    ).digest()\n    return {\n        \"POLY-ADDRESS\": WALLET_ADDRESS,\n        \"POLY-SIGNATURE\": base64.b64encode(signature).decode(),\n        \"POLY-TIMESTAMP\": timestamp,\n        \"POLY-API-KEY\": API_KEY,\n        \"POLY-PASSPHRASE\": API_PASSPHRASE\n    }\n\ndef on_message(ws, message):\n    data = json.loads(message)\n    event_type = data.get(\"event_type\")\n\n    if event_type == \"trade\":\n        # YOUR FILL - order matched!\n        status = data.get(\"status\")  # MATCHED, MINED, CONFIRMED, FAILED\n        print(f\"FILL: {data['side']} {data['size']} @ {data['price']}\")\n        print(f\"  Status: {status}\")\n        print(f\"  Trade ID: {data['id']}\")\n        print(f\"  Market: {data['market']}\")\n\n        if status == \"CONFIRMED\":\n            print(\"  ✓ Trade confirmed on-chain!\")\n        elif status == \"FAILED\":\n            print(\"  ✗ Trade failed - check logs\")\n\n    elif event_type == \"order\":\n        order_type = data.get(\"type\")  # PLACEMENT, UPDATE, CANCELLATION\n        print(f\"ORDER {order_type}: {data['side']} {data['original_size']} @ {data['price']}\")\n        print(f\"  Filled: {data.get('size_matched', 0)}\")\n\n        if order_type == \"CANCELLATION\":\n            print(\"  Order cancelled\")\n\ndef on_open(ws):\n    # Subscribe with auth\n    ws.send(json.dumps({\n        \"type\": \"subscribe\",\n        \"channel\": \"user\",\n        \"auth\": get_auth_headers(),\n        # Optional: filter to specific market\n        # \"markets\": [CONDITION_ID]\n    }))\n\nws = websocket.WebSocketApp(\n    \"wss:\u002F\u002Fws-subscriptions-clob.polymarket.com\u002Fws\u002Fuser\",\n    on_message=on_message,\n    on_open=on_open\n)\nws.run_forever()\n```\n\n### Message Types Summary\n\n**Market Channel:**\n| Event | Trigger | Key Fields |\n|-------|---------|------------|\n| `book` | Subscribe, trades affect book | bids, asks, timestamp |\n| `price_change` | Order placed\u002Fcancelled | price, size, side |\n| `last_trade_price` | Trade executed | price, size, side |\n| `tick_size_change` | Price extreme (>0.96 or \u003C0.04) | old_tick_size, new_tick_size |\n\n**User Channel:**\n| Event | Trigger | Key Fields |\n|-------|---------|------------|\n| `trade` | Your order filled | status, side, size, price, market |\n| `order` | Order placed\u002Fupdated\u002Fcancelled | type (PLACEMENT\u002FUPDATE\u002FCANCELLATION), size_matched |\n\n### Trade Status Flow\n\n```\nMATCHED → MINED → CONFIRMED (success)\n                → RETRYING → CONFIRMED\u002FFAILED\n```\n\n### Keepalive\n\nSend PING every 10 seconds to keep connection alive:\n```python\nimport threading\n\ndef send_ping():\n    while True:\n        ws.send(json.dumps({\"type\": \"ping\"}))\n        time.sleep(10)\n\nthreading.Thread(target=send_ping, daemon=True).start()\n```\n\n### Real-Time Data Client (Alternative)\n\nPolymarket also provides `@polymarket\u002Freal-time-data-client` for TypeScript:\n\n```typescript\nimport { RealTimeDataClient } from \"@polymarket\u002Freal-time-data-client\";\n\nconst client = new RealTimeDataClient({\n    onMessage: (msg) => console.log(msg),\n    onConnect: (c) => {\n        \u002F\u002F Subscribe to user fills with auth\n        c.subscribe({\n            subscriptions: [{\n                topic: \"clob_user\",\n                type: \"*\",\n                clob_auth: {\n                    key: API_KEY,\n                    secret: API_SECRET,\n                    passphrase: API_PASSPHRASE\n                }\n            }]\n        });\n    }\n});\n\nclient.connect();\n```\n\n---\n\n## No RPC Needed - CLOB Handles Everything\n\n| Operation | Method |\n|-----------|--------|\n| Get positions | `GET \u002Fdata\u002Fpositions?user={address}` via Gamma API |\n| Get balance | `client.get_balance_allowance()` |\n| Place orders | `client.create_and_post_order()` |\n| Get fills | User WebSocket channel |\n| Get prices | `client.get_order_book()` or Market WebSocket |\n| Cancel orders | `client.cancel()` |\n\nThe only time you might use RPC is to check on-chain token balances independently, but even that's available via Gamma API positions endpoint.\n",{"name":5,"emoji":40,"gates":41,"description":7},"💰",{"envs":42},[43,44,45,46],"POLY_API_KEY","POLY_API_SECRET","POLY_API_PASSPHRASE","PRIVATE_KEY","main","f2ec4b3b9133d34eeaf9b38e4b0a97e8e5705a7f","benchmarks\u002Ffinal\u002Fskills\u002Fasset1__alsk1992--trading-polymarket",0,"https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard","https:\u002F\u002Fgithub.com\u002FJSGforever","2026-08-29 18:27:56",{"source":8,"skillName":5,"commands":55,"prompt":65,"zipAvailable":66},[56,59,62],{"tool":57,"command":58},"npx","npx skills add JSGforever\u002Fskillguard --skill trading-polymarket",{"tool":60,"command":61},"bunx","bunx skills add JSGforever\u002Fskillguard --skill trading-polymarket",{"tool":63,"command":64},"pnpm","pnpm dlx skills add JSGforever\u002Fskillguard --skill trading-polymarket","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__alsk1992--trading-polymarket\u002FSKILL.md",true,[68],{"path":69,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":72,"sourceHtmlUrl":73},"index.ts","SCRIPT","脚本",53299,"https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__alsk1992--trading-polymarket\u002Findex.ts",[75,101,111,137,156,176],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":35},"01M71HY2SNXBA9Q00WZDTZQ31Z","skillguard-codex-scanner","Hybrid deterministic+LLM agent-skill security scanner. Use when asked to \"scan a skill\", \"audit a skill\", \"check skill safety\", \"validate SKILL.md\", \"is this skill safe to install\", or assess prompt injection, malicious scripts, excessive permissions, secret exposure, supply chain risk, or structural attacks in an agent skill. Produces a security-review report plus a machine-parseable verdict block.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fsrc\u002Fskillguard\u002Fstatic_scanner\u002Fskillguard-codex-scanner\u002FSKILL.md",[],[82,83,84,85,86,87,88,89,90,33,91,92,93,94,95,96,97,98,99,100],"scanner","skillguard codex scanner","skillguard","codex","chain","skill security","security-review","review report","structural","prompt injection","security scanner","when","review","malicious","permissions","exposure","audit","scripts","safe",{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":105,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":35},"01M71HY0SPKTT3S27BC2HPAC5M","data-exfiltrator","Analyzes data files","MIT","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Fsmoke-one-skill\u002Fasset1__cisco-ai-defense--data-exfiltrator\u002FSKILL.md",[],[29,109,110],"data exfiltrator","files",{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":35},"01M71HXVS9EMN44BGDW215FZ72","real-time-collaboration-engine","Build real-time collaborative editing with WebSockets, OT\u002FCRDT conflict resolution, and presence awareness. Implements cursor tracking, optimistic updates, and offline sync. Use for collaborative editors, whiteboards, video editing. Activate on \"real-time collaboration\", \"WebSocket sync\", \"multiplayer editing\", \"CRDT\", \"presence awareness\". NOT for simple chat, request-response APIs, or single-user apps.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__curiositech--real-time-collaboration-engine\u002FSKILL.md",[],[118,119,120,121,122,123,124,125,126,127,128,129,32,130,131,132,133,134,135,136],"time","real time collaboration engine","real time collaboration","collaboration","engine","real time","Video","reliability","video editing","performance","conflict resolution","presence","apps","updates","Bash","activate","optimizer","react","streaming",{"skillNo":138,"name":139,"nameZh":6,"description":140,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":141,"categories":142,"keywords":143,"publishedAt":35},"01M71HXP6CTY4KFN0QVMMN0V7J","react-performance-optimizer","Optimize React apps for 60fps performance. Implements memoization, virtualization, code splitting, bundle optimization. Use for slow renders, large lists, bundle bloat. Activate on \"React performance\", \"slow render\", \"useMemo\", \"bundle size\", \"virtualization\". NOT for backend optimization, non-React frameworks, or premature optimization.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__curiositech--react-performance-optimizer\u002FSKILL.md",[],[127,144,134,135,145,146,147,148,149,150,118,151,152,130,132,153,133,136,154,155],"react performance optimizer","react performance","performance optimizer","app","nextjs","expert","re","render","2025","code","router","strategies",{"skillNo":157,"name":158,"nameZh":6,"description":159,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":160,"categories":161,"keywords":162,"publishedAt":35},"01M71HXH7QXSQB4QTDZ7SP7YXQ","llm-streaming-response-handler","Build production LLM streaming UIs with Server-Sent Events, real-time token display, cancellation, error recovery. Handles OpenAI\u002FAnthropic\u002FClaude streaming APIs. Use for chatbots, AI assistants, real-time text generation. Activate on \"LLM streaming\", \"SSE\", \"token stream\", \"chat UI\", \"real-time AI\". NOT for batch processing, non-streaming APIs, or WebSocket bidirectional chat.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__curiositech--llm-streaming-response-handler\u002FSKILL.md",[],[163,136,164,165,166,167,127,118,168,169,170,132,133,134,171,135,172,173,174,175],"llm streaming response handler","handler","error","processing","retry","chat ui","error recovery","critical","batch","display","text","server","read",{"skillNo":177,"name":178,"nameZh":6,"description":179,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":180,"categories":181,"keywords":182,"publishedAt":35},"01M71HXCB0E1YRKYW1Y8T0Y106","github-actions-pipeline-builder","Build production CI\u002FCD pipelines with GitHub Actions. Implements matrix builds, caching, deployments, testing, security scanning. Use for automated testing, deployments, release workflows. Activate on \"GitHub Actions\", \"CI\u002FCD\", \"workflow\", \"deployment pipeline\", \"automated testing\". NOT for Jenkins\u002FCircleCI, manual deployments, or non-GitHub repositories.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__curiositech--github-actions-pipeline-builder\u002FSKILL.md",[],[183,184,185,186,187,188,189,125,149,190,191,192,133,155,193,175,194,195,196,197],"github actions pipeline builder","actions","github actions","pipeline builder","github","builder","pipeline","testing","ci","workflows","run","release","write","edit","git"]