API Reference
Complete reference for PolyOracle AI's REST API and LangGraph integration.
Base Configuration
Base URL: http://localhost:2024
(default LangGraph dev server)
Content-Type: application/json
Authentication: None required for local development
Core Endpoints
Health Check
Check if the backend service is running.
Request:
GET /health
Response:
{
"status": "healthy",
"version": "0.1.0",
"timestamp": "2024-01-15T10:30:00Z"
}
Market Analysis
Analyze a specific prediction market.
Request:
POST /analyze
Content-Type: application/json
{
"market_id": "0x123abc...",
"research_depth": 3,
"force_refresh": false
}
Parameters:
market_id
(string, required): Polymarket market identifierresearch_depth
(integer, optional): Research depth level (1-5, default: 3)force_refresh
(boolean, optional): Skip cached analysis (default: false)
Response:
{
"market_id": "0x123abc...",
"market_question": "Will Bitcoin reach $100K by December 2024?",
"analysis": {
"decision": "BUY",
"outcome": "YES",
"confidence": 0.78,
"recommended_amount": 150,
"rationale": "Strong research consensus supports higher probability..."
},
"market_data": {
"current_price_yes": 0.65,
"current_price_no": 0.35,
"volume_24h": 45230,
"liquidity_total": 234500,
"spread": 0.023
},
"research_summary": {
"sources_analyzed": 15,
"research_confidence": 0.82,
"key_findings": [
"Institutional adoption increasing",
"Technical indicators bullish"
]
},
"timestamp": "2024-01-15T10:30:00Z"
}
Execute Trade
Execute a trade based on analysis results.
Request:
POST /trade
Content-Type: application/json
{
"market_id": "0x123abc...",
"side": "buy",
"outcome": "yes",
"amount": 100,
"max_slippage": 0.02,
"require_approval": true
}
Parameters:
market_id
(string, required): Market identifierside
(string, required): "buy" or "sell"outcome
(string, required): "yes" or "no"amount
(number, required): USDC amount to trademax_slippage
(number, optional): Maximum acceptable slippage (default: 0.05)require_approval
(boolean, optional): Require human approval (default: true)
Response:
{
"trade_id": "trade_456def",
"status": "pending_approval",
"market_id": "0x123abc...",
"side": "buy",
"outcome": "yes",
"amount": 100,
"estimated_price": 0.67,
"estimated_tokens": 149.25,
"approval_required": true,
"expires_at": "2024-01-15T11:00:00Z"
}
Approve Trade
Approve a pending trade for execution.
Request:
POST /trade/{trade_id}/approve
Response:
{
"trade_id": "trade_456def",
"status": "executing",
"transaction_hash": "0xabc123...",
"execution_started_at": "2024-01-15T10:35:00Z"
}
Portfolio Status
Get current portfolio information.
Request:
GET /portfolio
Response:
{
"wallet_address": "0x789ghi...",
"usdc_balance": 1250.50,
"total_portfolio_value": 1435.75,
"unrealized_pnl": 185.25,
"positions": [
{
"market_id": "0x123abc...",
"market_question": "Will Bitcoin reach $100K by December 2024?",
"outcome": "yes",
"tokens_held": 149.25,
"avg_purchase_price": 0.67,
"current_price": 0.73,
"unrealized_pnl": 8.95,
"position_value": 108.95
}
],
"recent_trades": [
{
"trade_id": "trade_456def",
"timestamp": "2024-01-15T10:35:00Z",
"market_question": "Will Bitcoin reach $100K by December 2024?",
"side": "buy",
"outcome": "yes",
"amount": 100,
"tokens_received": 149.25,
"avg_price": 0.67,
"status": "completed"
}
]
}
Market List
Get available markets for analysis.
Request:
GET /markets?category=politics&min_volume=1000&limit=20&offset=0
Parameters:
category
(string, optional): Filter by market categorymin_volume
(number, optional): Minimum 24h volume in USDCmin_liquidity
(number, optional): Minimum total liquiditylimit
(number, optional): Number of markets to return (default: 20)offset
(number, optional): Pagination offset (default: 0)
Response:
{
"markets": [
{
"market_id": "0x123abc...",
"question": "Will Bitcoin reach $100K by December 2024?",
"category": "crypto",
"end_date": "2024-12-31T23:59:59Z",
"current_price_yes": 0.65,
"volume_24h": 45230,
"liquidity_total": 234500,
"last_analyzed": "2024-01-15T09:15:00Z"
}
],
"total_count": 156,
"has_more": true
}
LangGraph Integration
Graph Execution
Execute the full analysis graph for a market.
Request:
POST /graph/run
Content-Type: application/json
{
"config": {
"market_id": "0x123abc...",
"research_depth": 3,
"enable_trading": true
},
"stream": false
}
Response (Complete execution):
{
"run_id": "run_789xyz",
"status": "completed",
"result": {
"final_decision": "BUY",
"confidence": 0.78,
"analysis_complete": true
},
"execution_time": 45.2,
"nodes_executed": [
"fetch_market_data",
"research_market",
"analyze_market",
"make_decision"
]
}
Streaming Execution
Stream real-time updates during graph execution.
Request:
POST /graph/stream
Content-Type: application/json
{
"config": {
"market_id": "0x123abc...",
"research_depth": 3
}
}
Response (Server-Sent Events):
data: {"event": "node_start", "node": "fetch_market_data", "timestamp": "..."}
data: {"event": "node_complete", "node": "fetch_market_data", "result": {...}}
data: {"event": "node_start", "node": "research_market", "timestamp": "..."}
data: {"event": "research_update", "progress": 0.3, "sources_found": 5}
data: {"event": "node_complete", "node": "research_market", "result": {...}}
data: {"event": "graph_complete", "final_result": {...}}
Graph Status
Check the status of a running graph execution.
Request:
GET /graph/runs/{run_id}/status
Response:
{
"run_id": "run_789xyz",
"status": "running",
"current_node": "research_market",
"progress": 0.6,
"started_at": "2024-01-15T10:30:00Z",
"estimated_completion": "2024-01-15T10:32:30Z",
"nodes_completed": [
"fetch_market_data"
],
"nodes_remaining": [
"analyze_market",
"make_decision"
]
}
Configuration Endpoints
Update Configuration
Update runtime configuration without restarting.
Request:
PUT /config
Content-Type: application/json
{
"research": {
"default_depth": 3,
"sources_per_query": 10,
"max_research_time": 300
},
"trading": {
"min_confidence": 0.7,
"max_position_size": 500,
"require_approval": true
},
"risk": {
"max_daily_trades": 10,
"max_total_exposure": 2000
}
}
Response:
{
"status": "updated",
"config": {
"research": {...},
"trading": {...},
"risk": {...}
},
"updated_at": "2024-01-15T10:40:00Z"
}
Get Configuration
Retrieve current configuration.
Request:
GET /config
Response:
{
"research": {
"default_depth": 3,
"sources_per_query": 10,
"max_research_time": 300
},
"trading": {
"min_confidence": 0.7,
"max_position_size": 500,
"require_approval": true
},
"risk": {
"max_daily_trades": 10,
"max_total_exposure": 2000
}
}
Error Responses
All endpoints use consistent error response format:
{
"error": {
"code": "INVALID_MARKET_ID",
"message": "Market ID must be a valid hex string",
"details": {
"provided": "invalid_id",
"expected_format": "0x[a-fA-F0-9]{40}"
}
},
"timestamp": "2024-01-15T10:30:00Z"
}
Common Error Codes
INVALID_MARKET_ID
: Invalid or malformed market identifierMARKET_NOT_FOUND
: Market does not exist or is delistedINSUFFICIENT_BALANCE
: Not enough USDC for tradeAPI_LIMIT_EXCEEDED
: Rate limit or quota exceededANALYSIS_TIMEOUT
: Analysis took too long to completeTRADE_REJECTED
: Trade was rejected by exchangeCONFIG_INVALID
: Invalid configuration parameters
Python Client Example
import requests
import json
class PolyTradeClient:
def __init__(self, base_url="http://localhost:2024"):
self.base_url = base_url
def analyze_market(self, market_id, research_depth=3):
"""Analyze a market and get trading recommendation."""
response = requests.post(
f"{self.base_url}/analyze",
json={
"market_id": market_id,
"research_depth": research_depth
}
)
response.raise_for_status()
return response.json()
def execute_trade(self, market_id, side, outcome, amount):
"""Execute a trade with human approval."""
response = requests.post(
f"{self.base_url}/trade",
json={
"market_id": market_id,
"side": side,
"outcome": outcome,
"amount": amount,
"require_approval": True
}
)
response.raise_for_status()
return response.json()
def get_portfolio(self):
"""Get current portfolio status."""
response = requests.get(f"{self.base_url}/portfolio")
response.raise_for_status()
return response.json()
# Usage example
client = PolyTradeClient()
analysis = client.analyze_market("0x123abc...", research_depth=3)
if analysis["analysis"]["confidence"] > 0.7:
trade = client.execute_trade(
market_id="0x123abc...",
side="buy",
outcome="yes",
amount=100
)
print(f"Trade pending: {trade['trade_id']}")
Rate Limits
- Analysis requests: 10 per minute per IP
- Trade requests: 5 per minute per wallet
- Portfolio requests: 60 per minute per IP
- Configuration updates: 1 per minute per IP
Webhooks (Future Feature)
Webhook support for real-time notifications:
{
"webhook_url": "https://your-app.com/webhooks/polytrade",
"events": [
"trade_executed",
"analysis_completed",
"portfolio_updated"
],
"secret": "your_webhook_secret"
}
Next Steps
- Quick Start Guide - Get started with the API
- Trading Guide - Learn about trade execution
- Troubleshooting - Common API issues
Need help with API integration? Check the GitHub repository for additional examples and community support.