Polymarket Smart Contract & DeFi Research

Research Date: December 22, 2025 Focus: Smart contract architecture, direct trading opportunities, DeFi integrations, and market making strategies


Executive Summary

Polymarket operates as a hybrid-decentralized exchange on Polygon with a Central Limit Order Book (CLOB) for off-chain matching and on-chain settlement. While the API provides convenience, direct smart contract interaction offers potential advantages in latency and control. The most profitable opportunities appear to be:

  1. Automated Market Making: $200-800/day reported earnings through liquidity provision + rewards
  2. Arbitrage: Multi-market and cross-platform opportunities (Polymarket-Kalshi, internal arbs)
  3. Leverage via Gondor: 2x leverage on positions (up to 4-5x planned for 2026)
  4. DeFi Collateral: Using positions as collateral to free up capital

Bottom Line: Market making with liquidity rewards is currently the most repeatable income stream. Direct contract trading offers marginal speed improvements but requires significant infrastructure.


1. Polymarket's Contract Architecture

Core Contracts (Polygon Mainnet - Chain ID 137)

Contract Address Purpose
CTF Exchange 0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E Main exchange for binary markets (YES/NO)
NegRisk Exchange 0xC5d563A36AE78145C45a50134d48A1215220f80a Exchange for multi-outcome markets
Conditional Tokens 0x4D97DCd97eC945f40cF65F87097ACe5EA0476045 Gnosis CTF contract - manages outcome tokens
Collateral (USDC) 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174 USDC token on Polygon
UMA Adapter 0x6A9D222616C90FcA5754cd1333cFD9b7fb6a4F74 Oracle adapter for market resolution
NegRisk Fee Module 0x78769d50be1763ed1ca0d5e878d93f05aabff29e Fee management for NegRisk markets

Sources: - CTF Exchange on PolygonScan - Polymarket CTF Documentation

Architecture Overview

Hybrid-Decentralized Model: - Off-chain: Order creation, matching, and management - On-chain: Settlement, execution, and custody - Operator: Matches orders but cannot set prices or execute unauthorized trades

Order Flow: 1. Users create EIP-712 signed orders off-chain 2. Operator matches orders without on-chain gas cost 3. Matched orders trigger on-chain execution via CTFExchange 4. Settlement happens atomically and non-custodially

Proxy Wallet System: - Each user gets a 1-of-1 multisig on Polygon - Enables atomic multi-step transactions - Gas Station Network relayers pay gas fees - User positions (ERC1155) and USDC (ERC20) stored in proxy

Key Innovation: Meta-transactions eliminate visible gas costs, solving the UX friction that killed earlier prediction markets like Augur ($50+ gas during congestion).

Sources: - How Polymarket Works - RockNBlock - CLOB Introduction - Polymarket Docs

Token Architecture (Gnosis CTF)

ERC1155 Outcome Tokens: - Each market creates a pair: YES token + NO token - Backed by 1 USDC collateral - Unique positionId ties token to specific outcome - Winning token redeems for 1 USDC, losing token worth 0

Split & Merge Mechanism: - Split: 1 USDC → 1 YES + 1 NO token - Merge: 1 YES + 1 NO → 1 USDC (instant, no fees) - Ensures YES + NO prices always sum to ~$1.00

No Simple Arbitrage: Unlike some prediction markets, Polymarket's split/merge mechanism prevents YES + NO < $1.00 arbitrage opportunities on the same market.

Sources: - Outcome Tokens Deep Dive - Polymarket Overview


2. Direct Contract Trading vs API

Can We Interact Directly?

Yes. Polymarket provides multiple interaction methods:

  1. CLOB API (Easiest)
  2. Python: py-clob-client
  3. TypeScript: clob-client
  4. REST + WebSocket support

  5. Direct Contract Calls (Advanced)

  6. Via Web3.py or Ethers.js
  7. Requires understanding EIP-712 signing
  8. Must manage allowances manually

Advantages of Direct Contract Trading

Aspect API Direct Contract
Latency ~50-200ms Potentially 10-50ms faster
Control Limited to API features Full contract access
Complexity Easy Requires Web3 expertise
Gas Costs Abstracted (meta-txs) Must pay or relay gas
Features Most use cases Advanced strategies

Reality Check: For most strategies, the API latency is NOT the bottleneck. The limiting factors are: - Order matching: Centralized operator processes all matches - On-chain settlement: Polygon block time (~2 seconds) - Market inefficiency: Opportunities last seconds to minutes, not milliseconds

When Direct Contract Interaction Makes Sense: - Custom order types not supported by API - Integration with other smart contracts (e.g., DeFi protocols) - MEV-style strategies requiring atomic execution - Building on top of Polymarket (e.g., derivatives protocols)

Gas Costs

Polymarket Gas Costs are Near Zero: - Polygon Layer-2: Transactions cost fractions of a cent - Meta-transactions: Platform subsidizes gas for most operations - Trading: No gas fees for users on standard trades

Gas is Required For: - Deposits: Ethereum mainnet → Polygon bridge (~$3-10 depending on ETH gas) - Withdrawals: Polygon → Ethereum mainnet (~$3-10) - Allowances: First-time approval of USDC/CTF tokens (if not using email wallet)

Cost Comparison: - API Trading: Effectively free (meta-transactions) - Direct Contract: Same cost (can use meta-txs or pay ~$0.01/tx on Polygon)

Bottom Line: Gas costs are negligible on Polygon. This is NOT like trading on Ethereum mainnet.

Sources: - Trading Fees - Polymarket Docs - How Crypto Powers Polymarket - Benzinga

Speed Advantages

Minimal in Practice: - Both API and direct contracts use the same operator for matching - Settlement is identical (on-chain via CTFExchange) - Latency gains: 10-50ms at most

Where Speed Matters: - Arbitrage bots: Every millisecond counts in competitive arb - Market making: Faster quote updates in volatile conditions - MEV strategies: Atomic bundling with other protocols

Where Speed Doesn't Matter: - Statistical arbitrage: Edges persist for minutes/hours - Liquidity provision: Orders sit on book for extended periods - Value betting: Fundamental analysis, not latency-sensitive

Features Not Available via API

Based on research, the standard CLOB API covers ~95% of trading needs. Direct contract access might enable:

  1. Atomic Multi-Protocol Strategies:
  2. Borrow from Gondor + place bet in single transaction
  3. Arbitrage across DEX + Polymarket atomically
  4. Flash loan strategies

  5. Custom Order Types:

  6. Conditional orders based on other markets
  7. Algorithmic repricing beyond standard limit orders

  8. Advanced Position Management:

  9. Batch split/merge operations
  10. Direct redemption after resolution
  11. Custom collateral management

Verdict: For 99% of traders, the API is sufficient and easier. Direct contract interaction is for advanced DeFi integrations.

Sources: - py-clob-client GitHub - CTFExchange Contract


3. DeFi Integration Opportunities

A. Using Polymarket Positions as Collateral

Gondor Protocol - NOW LIVE

Gondor launched in December 2025 as the first DeFi lending protocol specifically for Polymarket positions.

How It Works: 1. Deposit your YES/NO positions (ERC1155 tokens) 2. Borrow up to 50-70% of position value in USDC 3. Use borrowed USDC for other trades or opportunities 4. Repay loan to withdraw collateral

Leverage Mechanism: - Current: 2x leverage via looping (beta launch Dec 12, 2025) - Planned: 4x-5x leverage by early 2026 - Strategy: Borrow against position → Deploy into second position → Repeat

Example Leverage Trade: 1. Buy $1,000 of YES shares on "Trump wins 2028" 2. Deposit in Gondor, borrow $500 USDC (50% LTV) 3. Buy $500 more YES shares 4. Total exposure: $1,500 with $1,000 capital = 1.5x leverage 5. For 2x: Deposit second position, borrow again

Capital Efficiency Use Case: - You bet $10,000 on "2028 Presidential Election" (resolves in 3+ years) - Borrow $5,000 against position - Use $5,000 for short-term arb opportunities - Keep long-term position exposure + trade with freed capital

Security: - Built on Morpho lending protocol ($5B TVL) - 34 audits by 14 security firms - Non-custodial (you control withdrawal after repayment) - Smart contract risk exists but mitigated by Morpho's track record

Risks: - Liquidation: If position value drops, you can be liquidated - Cascade risk: Leveraged position unwinding in thin markets - Oracle risk: Position valuation depends on accurate pricing - Smart contract risk: DeFi protocol vulnerabilities

Funding & Traction: - $2.5M angel round (Maven11, Prelude, Castle Island Ventures) - Currently in private beta (limited access)

Money-Making Opportunity: - Capital efficiency: Unlock liquidity from long-dated positions - Leverage trades: Amplify gains (and losses) on high-conviction bets - Yield strategies: Lend unlocked capital elsewhere while maintaining positions

Sources: - Gondor Official Site - Gondor Funding Announcement - Gondor Protocol Details

Traditional DeFi Lending (Aave/Compound): - No current integration with Polymarket positions - These platforms focus on standard crypto assets - Prediction market tokens not yet supported as collateral

B. Liquidity Pools & AMMs

Polymarket Has BOTH Order Book AND AMM:

Fixed Product Market Makers (FPMMs): - Deployed for each market upon creation - Constant product formula: YES × NO = k - Liquidity providers earn fees from trades - Separate from the main CLOB

How AMM Liquidity Provision Works:

  1. Add Liquidity:
  2. Deposit equal value of YES + NO shares
  3. Receive LP tokens representing pool share
  4. Earn fees proportional to pool ownership

  5. AMM Pricing:

  6. Prices rebalance after each trade
  7. YES + NO always sum to $1.00 (by design)
  8. Bonding curve determines individual prices

  9. LP Risks:

  10. Impermanent loss: Price shifts reduce LP value
  11. Resolution risk: Token becomes worth 0 or 1 (total loss for LPs)
  12. Adverse selection: Informed traders trade against LPs

Why AMM is Less Popular Than CLOB: - Order book provides better price discovery - Liquidity rewards only apply to CLOB (not AMM) - Active market makers prefer CLOB for control

AMM Still Useful For: - Guaranteed execution (no order matching needed) - Thin markets without active market makers - Automated strategies without order management

Sources: - Automated Market Making on Polymarket - Polymarket AMM Guide - Medium

C. Arbitrage Opportunities

Types of Arbitrage:

1. Multi-Market Combinatorial Arbitrage

When related markets have inconsistent probabilities: - Event A + Event B + Event C should sum to 100% (mutually exclusive) - If sum < 100%, buy all outcomes for guaranteed profit - If sum > 100%, no direct arb (can't short on Polymarket)

Example:

Market: "Who wins 2028 election?"
- Biden: 35%
- Trump: 40%
- Other: 20%
Total: 95% < 100%

Arbitrage: Buy 1 share of each for $0.95, guaranteed $1.00 payout = 5.3% profit

Real-World Profitability: - Opportunities exist for "a few seconds" according to research - Bots dominate this space (operating on Polygon nodes) - One address: $10K → $100K in 6 months via multi-option arb

2. Cross-Platform Arbitrage (Polymarket ↔ Kalshi)

Price discrepancies between platforms: - Same event, different prices - Buy low on one platform, sell high on another - Net profit = price difference - fees

Tools Available: - EventArb Calculator - tracks Kalshi, Polymarket, Robinhood, Interactive Brokers - GitHub bots for automated Poly-Kalshi arbitrage - Mirror markets between Polymarket and Opinion (newer platform)

Challenges: - Platform fees: Eat into profit margins - Transfer time: Capital locked during cross-platform transfers - Competition: Sophisticated bots dominate - Liquidity: Limited size on some markets

3. Statistical Convergence (Related Markets)

Not pure arbitrage, but mean-reversion strategy: - "Trump wins nomination" vs "Trump wins general election" - Temporarily diverge, should converge logically - Trade the spread, exit when correlation normalizes

Example from your codebase:

# From ARCHITECTURE.md:
# Statistical Convergence Engine
# Trade divergence between correlated markets
# - Event vs sub-event
# - Winner vs control markets
# - Mutually dependent political outcomes

Sources: - Unravelling Probabilistic Forest - ArXiv - Polymarket Arbitrage Strategies - Phemex - Polymarket-Kalshi Arbitrage Bot - GitHub

D. Cross-Chain Opportunities

Limited Direct Cross-Chain Arbitrage:

Polymarket lives entirely on Polygon. Cross-chain opportunities are indirect:

1. Bridge Arbitrage (USDC): - USDC price differences between Ethereum ↔ Polygon - Extremely rare (stablecoins maintain peg) - Requires large capital to overcome bridge fees

2. Collateral Efficiency: - Use ETH/other assets on mainnet as Aave collateral - Borrow USDC → Bridge to Polygon → Trade on Polymarket - Risk: Liquidation on Aave if collateral drops

3. Multi-Protocol Strategies: - Flash loan on Ethereum → Bridge to Polygon → Arb on Polymarket → Bridge back - High complexity, tight profit margins - Gas costs often exceed profits

Verdict: Cross-chain opportunities are mostly theoretical. Focus on Polygon-native strategies.


4. Automated Market Making - The Best Opportunity

Overview

Market making is currently the most profitable and repeatable strategy on Polymarket.

Liquidity providers (LPs) place limit orders on both sides of the market, earning: 1. Spread capture: Difference between buy and sell orders 2. Liquidity rewards: Polymarket pays bonuses for providing liquidity

Reported Earnings

Real-World Results: - Started with $10,000 capital - Early days: ~$200/day - At peak (scaled up + refined): $700-800/day - Strategy: Two-sided liquidity + Polymarket rewards program

Industry Estimates: - Market makers earned $20M+ on Polymarket in 2024 - Typical active maker: $200-800/day during busy periods - Top 0.5% of users made >$1,000 profit - Only 1.7% of users had >$50K trading volume

Caveat: Post-2024 election, total liquidity rewards decreased significantly. Current earnings likely lower.

Sources: - Automated Market Making on Polymarket - Polymarket MM Guide - PolyTrack

How It Works

Basic Strategy: 1. Place buy limit order slightly below market price (e.g., 0.48) 2. Place sell limit order slightly above market price (e.g., 0.52) 3. When both fill, profit = spread (0.52 - 0.48 = 0.04 = 4%) 4. Repeat continuously across many markets

Enhanced with Liquidity Rewards:

Polymarket pays bonuses based on: - Proximity to mid-price: Closer orders earn more - Two-sided liquidity: ~3x rewards for both sides vs one side - Market participation: Active markets get higher rewards - Spread tightness: Within max spread limit (e.g., 3 cents)

Rewards Formula (Simplified):

Reward ∝ (
    Size ×
    Spread_Quality ×
    Two_Sided_Bonus ×
    Market_Activity
)

Payout: Daily at ~midnight UTC

Liquidity Rewards Program Details

Qualifying Criteria: - Orders must be within "max spread" of mid-price (typically 3 cents) - For mid-price < $0.10, must have orders on BOTH sides - Minimum size cutoff varies by market

Example:

Market mid-price: $0.50
Max spread: 3 cents
Qualifying range: $0.47 - $0.53

Your orders:
- Buy at $0.49 ✓ (1 cent from mid)
- Sell at $0.51 ✓ (1 cent from mid)
- Two-sided bonus: ~3x multiplier

Market Selection: - Low volatility markets = lower risk - High reward markets = better returns - Balance: Stable markets with decent rewards

Sources: - Liquidity Rewards - Polymarket Docs - Polymarket Rewards Page

Implementation

Manual Market Making: - Monitor 5-20 markets - Update orders as prices move - Rebalance inventory periodically - Labor-intensive, doesn't scale

Automated Market Making (Recommended):

Bot Requirements: 1. Market selection: Filter for low volatility + high rewards 2. Order placement: Calculate optimal bid/ask spread 3. Inventory management: Balance YES/NO positions 4. Risk controls: Stop when volatility spikes 5. Multi-market scaling: Run on dozens of markets simultaneously

Python Implementation (High-Level):

from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs
from py_clob_client.order_builder.constants import BUY, SELL

# Initialize client
client = ClobClient(
    host="https://clob.polymarket.com",
    key=PRIVATE_KEY,
    chain_id=137,
    signature_type=1,  # Email wallet
    funder=FUNDER_ADDRESS
)
client.set_api_creds(client.create_or_derive_api_creds())

# Market making loop
for market in selected_markets:
    mid_price = get_mid_price(market)
    spread = 0.02  # 2 cent spread

    # Place both sides
    buy_order = OrderArgs(
        price=mid_price - spread/2,
        size=10.0,
        side=BUY,
        token_id=market.yes_token_id
    )

    sell_order = OrderArgs(
        price=mid_price + spread/2,
        size=10.0,
        side=SELL,
        token_id=market.yes_token_id
    )

    client.post_order(client.create_order(buy_order))
    client.post_order(client.create_order(sell_order))

Advanced Strategies: - Inventory skewing: Bias orders based on current position - Volatility adjustment: Widen spreads in unstable markets - News monitoring: Pause or exit before major events - Cross-market hedging: Offset risk across correlated markets

Risks

1. Adverse Selection: - Informed traders know outcome before you - Your buy order fills right before price crashes - Mitigate: Pause trading near resolution, monitor news

2. Inventory Risk: - Accumulate too much YES or NO - Market moves against position - Mitigate: Actively rebalance, set inventory limits

3. Volatility Spikes: - News breaks, prices gap 20-30% - Open orders fill at bad prices - Mitigate: Cancel orders on volatility, implement kill switch

4. Whale Manipulation: - Large trader crashes price from 0.99 → 0.90 - Panic selling amplifies move - Whales buy back cheap - Mitigate: Avoid thin markets, monitor for wash trading

5. Event Resolution: - Market resolves, you hold losing side - Total loss on that position - Mitigate: Close positions before resolution, hedge across markets

Profitability Analysis

Revenue Streams: 1. Spread capture: 2-4% per round-trip trade 2. Liquidity rewards: Variable, market-dependent 3. Rebates: None (Polymarket has no fees)

Cost Structure: - Capital: $10K-50K recommended for diversification - Infrastructure: API access (free), server costs (~$20-100/month) - Development: Bot development time (or hire developer) - Monitoring: Time spent managing/optimizing

Profit Math (Conservative):

Capital: $10,000
Markets: 20 simultaneous
Average spread: 2%
Fills per day: 10 round-trips
Liquidity rewards: $50/day

Daily earnings:
- Spread: 10 trades × $100 avg × 2% = $20
- Rewards: $50
Total: $70/day = ~$2,100/month = 21% monthly return

Note: Post-election reward reduction likely cuts this 30-50%

Realistic Expectations (Current Market): - Small capital (<$10K): $50-150/day - Medium capital ($10K-50K): $150-400/day - Large capital (>$50K): $400-700/day - Post-reward reduction: Cut estimates by 30-50%

Competition

Current State: - "Maybe one or two other bots providing liquidity across most markets" - Space is "incredibly underdeveloped compared to traditional crypto markets" - Most participants: Individual traders clicking buttons

Competitive Advantages: - Speed: Faster quote updates - Scale: More markets simultaneously - Sophistication: Better risk management - Capital: Deeper pockets for inventory management

Risk: As Polymarket grows, competition will intensify. Edges decay over time.

Recommendations

For Immediate Income: 1. Start with 5-10 stable markets 2. Build simple two-sided MM bot 3. Focus on liquidity rewards optimization 4. Scale gradually as you understand dynamics

For Long-Term Edge: 1. Invest in infrastructure (low-latency, reliable) 2. Develop sophisticated inventory management 3. Build news monitoring for event-driven pauses 4. Diversify across market types (politics, sports, crypto)

Realistic Goal: - $10K capital → $100-200/day initially - Optimize over 2-3 months → $300-500/day - Scale to $50K capital → $500-1000/day potential


5. Practical Recommendations: What Can We Actually Do To Make Money?

Tier 1: Highest Probability of Profit

1. Automated Market Making ($200-800/day potential)

Why: - Most repeatable strategy - Liquidity rewards provide base income - Spread capture adds upside - Low competition currently

How to Start: 1. Study existing rewards program 2. Build simple two-sided bot with py-clob-client 3. Start with 5 stable markets 4. Monitor daily, optimize spreads 5. Scale to 20-50 markets as confident

Capital Required: $10K-50K Time to Profitability: 2-4 weeks Risk Level: Medium (inventory risk, volatility)

2. Statistical Arbitrage ($50-300/day potential)

Why: - Your existing codebase supports this - Edges persist longer than pure arb - Less competitive than HFT arb

How: - Use existing correlation tracking - Identify mean-reverting market pairs - Trade divergences when Z-score > 2 - Exit when correlation normalizes

Capital Required: $5K-20K Time to Profitability: Immediate (if edge exists) Risk Level: Medium (correlation breakdown)

Tier 2: Moderate Opportunity

3. Multi-Market Combinatorial Arbitrage ($20-100/day potential)

Why: - True arbitrage (risk-free in theory) - Opportunities exist daily - Requires speed but not HFT-level

How: 1. Monitor multi-outcome markets 2. Calculate if sum < 100% 3. Buy all outcomes if profit > threshold 4. Hold to resolution

Capital Required: $5K-15K Time to Profitability: Immediate Risk Level: Low (true arb) but very competitive

Challenge: Bots dominate, opportunities last seconds

4. Leverage via Gondor (Risk amplifier, not standalone)

Why: - 2x leverage on high-conviction bets - Free up capital from long-dated positions

How: 1. Identify high-conviction, long-dated market 2. Buy position with 50% of capital 3. Deposit in Gondor, borrow 50% of value 4. Deploy borrowed capital in short-term strategies 5. Repay loan, keep both gains

Capital Required: $10K+ Time to Profitability: Depends on underlying strategy Risk Level: High (leverage amplifies losses)

Best Use: Combine with market making (use freed capital for MM)

Tier 3: Speculative / Future

5. Cross-Platform Arbitrage (Polymarket ↔ Kalshi)

Why: - Price discrepancies exist - Tools available (EventArb)

Challenges: - Capital locked during transfers - Platform fees eat profit - Competition from dedicated arb funds

Verdict: Possible but difficult. Focus on other opportunities first.

6. Direct Contract Trading / MEV

Why: - Potential for atomic multi-protocol strategies - Composability with other DeFi

Challenges: - Requires deep Web3 expertise - Limited edge over API for most strategies - Development time high

Verdict: Only pursue if building novel DeFi products on top of Polymarket.

Integration with Your Existing System

Based on your ARCHITECTURE.md and prd.md:

You Already Have: - Market data ingestion (CLOB API) - Orderbook management - Risk engine - Strategy framework - Backtesting infrastructure

Additions for Market Making:

  1. Liquidity Rewards Tracker:
  2. Query Polymarket rewards API
  3. Track which markets have high rewards
  4. Filter for low volatility + high reward ratio

  5. Inventory Manager:

  6. Track YES/NO positions per market
  7. Rebalance when skew exceeds threshold
  8. Implement position limits

  9. Market Making Strategy Module: python class MarketMakingStrategy(Strategy): def on_orderbook_update(self, market): # Cancel existing orders # Calculate new bid/ask based on: # - Mid price # - Target spread # - Current inventory # - Volatility # Place two-sided orders # Update inventory tracking

  10. Volatility Monitor:

  11. Calculate rolling price volatility
  12. Widen spreads or pause when volatility spikes
  13. Resume when market stabilizes

  14. News Event Detector:

  15. Monitor for market-moving events
  16. Pause trading X minutes before known events
  17. Gradually resume after

Additions for Gondor Integration:

  1. Position Valuation:
  2. Calculate current value of all positions
  3. Determine borrowing capacity (50% of value)

  4. Leverage Manager:

  5. Track loans from Gondor
  6. Monitor liquidation risk
  7. Automate repayment when optimal

  8. Capital Allocation:

  9. Allocate X% to long-term leveraged positions
  10. Allocate Y% to short-term MM/arb
  11. Rebalance based on performance

6. Technical Implementation Guide

Setting Up Direct Contract Trading

Prerequisites:

pip install web3 py-clob-client eth-account

Initialize Web3 Connection:

from web3 import Web3
from py_clob_client.config import get_contract_config

# Polygon RPC
w3 = Web3(Web3.HTTPProvider('https://polygon-rpc.com'))

# Get contract addresses
config = get_contract_config(chainID=137)  # Polygon mainnet

# CTF Exchange contract
exchange_address = config.exchange  # 0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E
collateral_address = config.collateral  # USDC
ctf_address = config.conditional_tokens

Set Allowances (Required for Direct Trading):

from web3 import Web3
from eth_account import Account

# Load account
private_key = "your_private_key"
account = Account.from_key(private_key)

# USDC token contract
usdc_abi = [...] # Standard ERC20 ABI
usdc_contract = w3.eth.contract(address=collateral_address, abi=usdc_abi)

# Approve CTF Exchange to spend USDC
allowance_amount = w3.to_wei(10000, 'mwei')  # USDC has 6 decimals
tx = usdc_contract.functions.approve(
    exchange_address,
    allowance_amount
).build_transaction({
    'from': account.address,
    'nonce': w3.eth.get_transaction_count(account.address),
    'gas': 100000,
    'gasPrice': w3.eth.gas_price
})

signed_tx = account.sign_transaction(tx)
tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)

Using py-clob-client (Recommended):

from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs, MarketOrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY, SELL

# Initialize client
HOST = "https://clob.polymarket.com"
CHAIN_ID = 137  # Polygon
PRIVATE_KEY = "your_private_key"

# For email wallet (Magic)
client = ClobClient(
    HOST,
    key=PRIVATE_KEY,
    chain_id=CHAIN_ID,
    signature_type=1,  # Email wallet
    funder="your_polymarket_proxy_address"  # Your Polymarket wallet
)

# For MetaMask / hardware wallet
client = ClobClient(
    HOST,
    key=PRIVATE_KEY,
    chain_id=CHAIN_ID,
    signature_type=0,  # Standard EOA
)

# Create API credentials
client.set_api_creds(client.create_or_derive_api_creds())

# Place limit order
order = OrderArgs(
    token_id="21742633143463906290569050155826241533067272736897614950488156847949938836455",
    price=0.52,
    size=10.0,
    side=BUY
)

signed_order = client.create_order(order)
response = client.post_order(signed_order)
print(f"Order placed: {response}")

# Place market order (Fill-or-Kill)
market_order = MarketOrderArgs(
    token_id="21742633143463906290569050155826241533067272736897614950488156847949938836455",
    amount=25.0,  # USDC amount
    side=BUY,
    order_type=OrderType.FOK
)

signed_mo = client.create_market_order(market_order)
response = client.post_order(signed_mo, OrderType.FOK)

Get Market Data:

# Get orderbook
book = client.get_order_book("token_id")
print(f"Best bid: {book['bids'][0]}")
print(f"Best ask: {book['asks'][0]}")

# Get last trade price
last_price = client.get_last_trade_price("token_id")

# Get your positions
balances = client.get_balances()

# Get open orders
orders = client.get_orders()

Market Making Bot (Simplified)

import time
from decimal import Decimal
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs
from py_clob_client.order_builder.constants import BUY, SELL

class SimpleMarketMaker:
    def __init__(self, client, token_id, spread=0.02):
        self.client = client
        self.token_id = token_id
        self.spread = Decimal(str(spread))
        self.active_orders = []

    def get_mid_price(self):
        """Calculate mid price from orderbook"""
        book = self.client.get_order_book(self.token_id)
        if book['bids'] and book['asks']:
            best_bid = Decimal(str(book['bids'][0]['price']))
            best_ask = Decimal(str(book['asks'][0]['price']))
            return (best_bid + best_ask) / 2
        return None

    def cancel_all_orders(self):
        """Cancel existing orders"""
        for order_id in self.active_orders:
            try:
                self.client.cancel_order(order_id)
            except:
                pass
        self.active_orders = []

    def place_orders(self):
        """Place two-sided orders"""
        mid = self.get_mid_price()
        if not mid:
            return

        # Calculate bid/ask prices
        bid_price = float(mid - self.spread/2)
        ask_price = float(mid + self.spread/2)

        # Size (could be dynamic based on inventory)
        size = 10.0

        # Place buy order
        buy_order = OrderArgs(
            token_id=self.token_id,
            price=bid_price,
            size=size,
            side=BUY
        )
        buy_resp = self.client.post_order(self.client.create_order(buy_order))

        # Place sell order
        sell_order = OrderArgs(
            token_id=self.token_id,
            price=ask_price,
            size=size,
            side=SELL
        )
        sell_resp = self.client.post_order(self.client.create_order(sell_order))

        # Track order IDs
        self.active_orders = [buy_resp['orderID'], sell_resp['orderID']]

    def run(self, update_interval=60):
        """Main loop"""
        while True:
            try:
                # Cancel old orders
                self.cancel_all_orders()

                # Place new orders at current mid price
                self.place_orders()

                # Wait before next update
                time.sleep(update_interval)

            except KeyboardInterrupt:
                self.cancel_all_orders()
                break
            except Exception as e:
                print(f"Error: {e}")
                time.sleep(5)

# Usage
client = ClobClient(...)
mm = SimpleMarketMaker(
    client=client,
    token_id="your_token_id",
    spread=0.02  # 2 cent spread
)
mm.run(update_interval=60)  # Update quotes every 60 seconds

Enhancements: - Inventory management (adjust size based on position) - Volatility monitoring (widen spread in volatile markets) - Multi-market support (run on 20+ markets) - Liquidity rewards optimization (stay within max spread) - Risk controls (max position limits, kill switch)

Accessing Contract Data via The Graph

Polymarket Subgraph:

import requests

SUBGRAPH_URL = "https://api.thegraph.com/subgraphs/name/polymarket/polymarket-subgraph"

query = """
{
  markets(first: 10, orderBy: volume, orderDirection: desc) {
    id
    question
    volume
    liquidityParameter
    outcomes {
      id
      value
    }
  }
}
"""

response = requests.post(SUBGRAPH_URL, json={'query': query})
data = response.json()

On-Chain Event Monitoring:

# Monitor OrderFilled events from CTFExchange
exchange_contract = w3.eth.contract(address=exchange_address, abi=exchange_abi)

# Get recent OrderFilled events
event_filter = exchange_contract.events.OrderFilled.create_filter(
    fromBlock='latest'
)

for event in event_filter.get_all_entries():
    print(f"Order filled: {event.args}")

7. Risk Assessment & Mitigation

Smart Contract Risks

Risk: CTFExchange or Conditional Tokens contract bug/exploit

Mitigation: - Contracts audited by Chainsecurity - Multiple years in production without incident - Non-custodial design limits exposure - Only risk capital you can afford to lose

Monitoring: - Watch for unusual on-chain activity - Follow Polymarket's official channels for security updates

Counterparty Risk

Risk: Polymarket operator censors orders or manipulates matching

Reality: - Operator privileges limited to order matching - Cannot set prices or execute unauthorized trades - Users can cancel orders on-chain independently - Settlement is non-custodial

Mitigation: - Polymarket has strong incentives to remain neutral (reputation, regulation) - Diversify across multiple platforms if doing large volume

Oracle Risk

Risk: UMA oracle resolves market incorrectly

Mitigation: - UMA uses "optimistic oracle" - disputed resolutions go to vote - Polymarket can re-resolve markets if UMA fails - Historical accuracy is high - Avoid markets with ambiguous resolution criteria

Regulatory Risk

Risk: US regulations change, platform access restricted

Context: - Polymarket settled with CFTC in 2022 - Currently blocks US IP addresses - Uses USDC (regulated stablecoin)

Mitigation: - Operate from allowed jurisdictions - Comply with platform ToS - Monitor regulatory developments - Have exit plan if regulations change

Market Risks

1. Liquidity Risk - Risk: Can't exit position at desired price - Mitigation: Focus on high-volume markets, check depth before entering

2. Event Risk - Risk: News breaks, market gaps sharply - Mitigation: Set stop-losses, avoid over-concentration, pause before known events

3. Manipulation Risk - Risk: Whales manipulate thin markets - Mitigation: Avoid low-liquidity markets, monitor for wash trading patterns

4. Inventory Risk (Market Making) - Risk: Accumulate too much of losing outcome - Mitigation: Active rebalancing, position limits, inventory skewing

5. Leverage Risk (Gondor) - Risk: Liquidation on leveraged positions - Mitigation: Conservative LTV ratios, monitor collateral value, have reserves


8. Competitive Landscape

Current State (Dec 2025)

Market Making: - "One or two other bots providing liquidity across most markets" - Space is "incredibly underdeveloped" - Most users: Retail traders clicking buttons

Arbitrage: - More competitive - Dedicated bots operating on Polygon nodes - Opportunities last "a few seconds" - Estimated $20M+ earned by arb traders in 2024

Value Betting: - Less competitive (requires fundamental analysis) - Not purely systematic - Combines ML, news analysis, domain expertise

Competitive Advantages to Build

1. Infrastructure - Low-latency connections (co-locate near Polygon RPC) - Reliable execution (handle API errors gracefully) - Monitoring & alerts (know immediately if something breaks)

2. Sophistication - Better risk management (inventory limits, volatility adjustments) - Multi-market strategies (correlations, hedging) - Automated news monitoring (pause before events)

3. Capital - Deeper pockets for inventory - Ability to weather drawdowns - Scale across more markets

4. Speed to Market - First movers get disproportionate rewards - Build MVP quickly, iterate based on data - Don't over-engineer before testing

Edge Decay Timeline

Short-term (3-6 months): - Current liquidity rewards likely to decrease - More sophisticated bots will enter - Easier opportunities will get arbitraged away

Medium-term (6-12 months): - Polymarket may adjust rewards program - Professional market makers may enter - Arbitrage becomes HFT-dominated

Long-term (12+ months): - Mature market structure - Tighter spreads, lower profits - Need continuous innovation to maintain edge

Strategy: Extract value now while competition is low. Build robust systems for long-term adaptability.


9. Conclusion & Action Plan

Key Findings Summary

  1. Polymarket uses a hybrid-decentralized model: Off-chain matching, on-chain settlement on Polygon
  2. Direct contract trading offers minimal advantages over API for most strategies
  3. Gas costs are negligible on Polygon (~fractions of a cent)
  4. Market making is the most profitable current opportunity: $200-800/day reported with liquidity rewards
  5. Gondor enables leveraging Polymarket positions: 2x currently, 4-5x planned
  6. Arbitrage exists but is highly competitive: Requires speed and sophisticated infrastructure
  7. DeFi integrations are emerging: Gondor for lending, potential for more

Phase 1: Market Making Foundation (Weeks 1-4)

  1. Week 1: Research & Setup
  2. Study Polymarket liquidity rewards program in detail
  3. Set up py-clob-client and test API access
  4. Identify 5-10 stable, high-reward markets

  5. Week 2: Build MVP Bot

  6. Implement simple two-sided market maker
  7. Add inventory tracking
  8. Deploy on 2-3 test markets with small size

  9. Week 3: Optimize & Scale

  10. Analyze fill rates, spread capture, rewards
  11. Tune spread widths and sizes
  12. Scale to 10-15 markets

  13. Week 4: Risk Management

  14. Add volatility monitoring
  15. Implement position limits
  16. Create kill switch for emergencies

Target: $100-300/day with $10-20K capital

Phase 2: Statistical Arbitrage Integration (Weeks 5-8)

  1. Leverage existing correlation tracking
  2. Identify mean-reverting market pairs
  3. Implement pairs trading module
  4. Backtest on historical data
  5. Deploy with small allocation (10-20% of capital)

Target: Additional $50-150/day

Phase 3: Leverage & Capital Efficiency (Weeks 9-12)

  1. Apply for Gondor beta access
  2. Identify long-dated, high-conviction markets
  3. Use Gondor to borrow against positions
  4. Deploy freed capital into MM/arb strategies
  5. Monitor liquidation risk carefully

Target: 1.5-2x capital efficiency

Phase 4: Advanced Strategies (Months 4-6)

  1. Multi-market combinatorial arbitrage
  2. Cross-platform arb (Polymarket ↔ Kalshi)
  3. News-driven event trading
  4. ML-based market selection

Target: Diversified strategy portfolio, reduced single-strategy risk

Capital Allocation

Conservative Approach ($20K total): - Market Making: $12K (60%) - Statistical Arb: $5K (25%) - Gondor Leverage: $3K (15%)

Aggressive Approach ($50K total): - Market Making: $25K (50%) - Statistical Arb: $10K (20%) - Gondor Leverage: $10K (20%) - Multi-Market Arb: $5K (10%)

Success Metrics

Track Weekly: - Total P&L (by strategy) - Sharpe ratio (risk-adjusted returns) - Win rate - Average profit per trade - Liquidity rewards earned - Inventory turnover - Max drawdown

Adjust When: - Strategy Sharpe < 1.0 for 2+ weeks - Drawdown exceeds 15% of capital - Liquidity rewards decrease significantly - Competition increases (tighter spreads, fewer fills)

Final Thoughts

Polymarket presents real opportunities for systematic profit, particularly in market making and arbitrage. The space is currently underdeveloped compared to traditional markets, creating an edge for sophisticated, automated traders.

However, edges decay. The current liquidity rewards and low competition won't last forever. The key is to:

  1. Move quickly: Build and deploy before competition intensifies
  2. Extract value now: Take advantage of current inefficiencies
  3. Build for adaptability: Systems should evolve as market matures
  4. Manage risk: Never risk capital you can't afford to lose
  5. Stay informed: Monitor for platform changes, regulatory updates, reward adjustments

The most successful traders won't be those with the fastest infrastructure or largest capital, but those who can continuously identify and exploit new inefficiencies as old ones disappear.


Sources & References

Official Documentation

Smart Contracts & Code

Market Making & Strategy

Arbitrage & Trading

DeFi Integration

Technical Deep Dives

Security & Audits


Last Updated: December 22, 2025 Next Review: Monitor liquidity rewards changes, Gondor beta launch, competitive landscape monthly

System Overview

Polymarket API

Market data source

Data Collector

Every 5 minutes

SQLite Database

Price history + trades

Strategy Engine

Signal generation

ML Model

XGBoost (72% acc)

Execution Engine

Paper trading

Dashboard

You are here!

Telegram

Alerts & updates

Trading Strategies

Each strategy looks for different market inefficiencies:

Dual Arbitrage Active

Finds when YES + NO prices don't add to 100%. Risk-free profit.

Mean Reversion Active

Buys when price drops too far from average, sells when it recovers.

Market Maker Active

Places bid/ask orders to capture the spread.

Time Arbitrage Active

Exploits predictable price patterns at certain hours.

ML Prediction Active

Uses machine learning to predict 6-hour price direction.

Value Betting Disabled

Finds underpriced outcomes based on implied probability.

Data Storage (Single Source of Truth)

All data lives on EC2. Local machines are for development only. The EC2 instance is the authoritative source for all market data, trades, and positions.
Database Purpose Location
market_history.db Price snapshots every 5 minutes (8.2 MB) EC2 (primary)
pqap_staging.db Trades, positions, P&L history EC2 (primary)
paper_trading_state.json Current portfolio state EC2 (primary)

Environment Architecture

EC2 (Production)

  • Runs 24/7
  • All databases live here
  • Executes all trades
  • Single source of truth

Local (Development)

  • For code changes only
  • Syncs code to EC2
  • No production data
  • Can be turned off

Environment Details

Component Details
Dashboard URL https://pqap.tailwindtech.ai
Server AWS EC2 (us-east-1)
SSL Let's Encrypt via Traefik
Mode Paper Trading (simulated)

How It Works (Simple Version)

1. Data Collection: Every 5 minutes, we fetch prices from Polymarket for 50 markets and save them to our database.

2. Analysis: Our strategies analyze this data looking for patterns - like prices that moved too far from normal, or markets where the math doesn't add up.

3. Signals: When a strategy finds an opportunity, it generates a "signal" - a recommendation to buy or sell.

4. Execution: The execution engine takes these signals and simulates trades (paper trading). Eventually, this will place real orders.

5. Monitoring: This dashboard shows you what's happening. Telegram sends alerts for important events.