Skip to content

Implement Polymarket Arbitrage Agent with Cross-Market Strategy#384

Open
Jay-Sojitra wants to merge 28 commits intoEmberAGI:nextfrom
Jay-Sojitra:agent-polymarket
Open

Implement Polymarket Arbitrage Agent with Cross-Market Strategy#384
Jay-Sojitra wants to merge 28 commits intoEmberAGI:nextfrom
Jay-Sojitra:agent-polymarket

Conversation

@Jay-Sojitra
Copy link

@Jay-Sojitra Jay-Sojitra commented Jan 21, 2026

High-Level Goal

Build a complete Polymarket arbitrage trading system:

  • Direct Polymarket API client (Gamma, CLOB, Data APIs)
  • Cross-market arbitrage strategy as LangGraph workflow
  • Frontend integration with user controls

Requirements

1. Polymarket Client Implementation

  • ✅ Fetch market data (Gamma API)
  • ✅ Get real-time prices (CLOB API)
  • ✅ Place orders (buy yes/no token)
  • ✅ Track order status
  • ✅ Fetch user positions and trading history (Data API)
  • ✅ Support USDC permit (EIP-2612) and CTF approvals
  • ✅ Handle wallet signing and transaction construction

2. Agent Workflow (LangGraph)

Strategy:
1) Intra-market arbitrage (YES+NO < $1.00)
2) Cross-market arbitrage (logical relationship violations)

  • LLM-based relationship detection (IMPLIES, REQUIRES, MUTUAL_EXCLUSION, EQUIVALENCE)

Lifecycle Management:

  • ✅ States: disabledwaiting-fundsrunningstoppingstopped
  • ✅ Operations: hire, fire, sync, cycle, updateApproval
  • ✅ Position tracking with P&L calculation
  • ✅ Transaction history

Execution:

  • ✅ Risk-based position sizing
  • ✅ Balance verification before trades
  • ✅ Manual approval mode (optional)
  • ✅ Paper trading mode (testing)

3. Frontend Integration

  • ✅ Agent detail page with lifecycle controls
  • ✅ Opportunities display (intra + cross-market)
  • ✅ Relationships table (detected logical links)
  • ✅ Positions and P&L tracking
  • ✅ Transaction history
  • ✅ Settings (risk params, LLM toggle, manual approval)
  • ✅ Approval flow (USDC permit + CTF approval)

Implementation Details

Architecture

Frontend (Next.js)
↓ (triggers cycle via runCommand)
LangGraph Workflow (15 nodes)
↓ (calls client methods)
Polymarket Client (Direct API Integration)
↓ (HTTP + blockchain calls)
Polymarket APIs (Gamma, CLOB, Data) + Polygon

Key Files

  • apps/agent-polymarket/src/clients/polymarketClient.ts - Direct API client
  • apps/agent-polymarket/src/clients/approvals.ts - USDC/CTF approval logic
  • apps/agent-polymarket/src/agent.ts - LangGraph workflow (15 nodes)
  • apps/agent-polymarket/src/strategy/* - Scanner, evaluator, executor, relationship detector
  • apps/web/src/components/polymarket/* - Frontend UI components
  • apps/web/src/hooks/usePolymarketPolling.ts - Frontend polling hook

Environment Variables Required

Backend (apps/agent-polymarket/.env):

  • A2A_TEST_AGENT_NODE_PRIVATE_KEY - Wallet for signing trades
  • POLY_FUNDER_ADDRESS - Wallet address
  • OPENAI_API_KEY - For LLM relationship detection
  • POLYGON_RPC_URL - Polygon RPC endpoint

Frontend (apps/web/.env):

  • NEXT_PUBLIC_POLY_POLL_INTERVAL_MS - Polling interval
    (default: 180000ms = 3 min)

Success Criteria

  • Agent finds arbitrage opportunities
  • Agent executes trades automatically
  • Frontend displays real-time data
  • User can approve/reject trades manually
  • P&L tracked accurately
  • Positions synced from Polymarket API
  • Auto-redemption of resolved markets

Steps to Run:

1. Setup environment

cd apps/agent-polymarket
cp .env.example .env and configure all variables

2. Setup web frontend

cd apps/web
Edit .env: Set NEXT_PUBLIC_POLY_POLL_INTERVAL_MS=180000 # 3 minutes
(default)

3. run from web-ag-ui

pnpm install
pnpm dev

4. Test agent

  • Navigate to localhost:3000/hire-agents/agent-polymarket
  • Click "Hire" → Sign USDC permit + CTF approval
  • Wait for cycles (default: 3 min)
  • Verify opportunities appear
  • Check positions and transactions tabs

Checklists

Code Quality

  • Code follows project conventions and style guidelines
  • TypeScript compilation passes (pnpm build)
  • Linting passes (pnpm lint)
  • Error handling implemented appropriately

Documentation

  • Code is self-documenting with clear function names
  • Complex logic includes comments
  • Environment variables documented
  • Comprehensive docs added (architecture, strategy, workflow,
    flow)

Agent Specific

  • LangGraph workflow properly defined
  • Error handling for external API failures (timeouts, rate
    limits)
  • Rate limiting respected (via API client)
  • Configuration options documented

Breaking Changes:

  • None (new feature)

Additional Context

Architecture:
Frontend (Next.js) → LangGraph Agent → Polymarket Client →
Polymarket APIs + Polygon
↑ ↓ ↓
└────────────── State Sync ──────────────┘

Why Direct Client vs Plugin:

  • Simpler implementation - direct API calls (plugin can be integrated later through ember API)
  • No intermediate abstraction layer needed
  • Full control over API interactions
  • Easier debugging and error handling

Key Features:

  • Dual Strategy: Intra-market (simple) + Cross-market (advanced)
  • LLM Detection: Finds novel relationships patterns can't catch
  • Real-time UI: Live opportunities, positions, P&L
  • Manual Approval: Optional review before execution
  • Risk Management: Portfolio-based position sizing, balance checks
  • Auto-sync: Positions every 5th cycle, redemptions every 10th cycle
  • Paper Trading: Test strategies without real capital

Documentation Added:

  • docs/01-architecture-overview.md - System architecture
  • docs/02-strategy-deep-dive.md - Trading strategies with examples
  • docs/03-langgraph-workflow.md - Complete workflow guide
  • docs/FLOW.md - User flow and integration guide
  • docs/strategy-overview.md - Quick reference

… and price rounding functionality

- Added a new function to fetch markets and their prices for the Polymarket agent.
- Implemented price rounding to the market's tick size to prevent invalid tick size errors.
- Updated the agent context to dynamically route to the correct agent based on the URL.
- Adjusted the API route to handle multiple agents and improved error handling for agent name extraction.
- Refactored the agent connection logic to ensure proper remounting when switching agents.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant