AI Agent Integration
Seesaw provides first-class support for autonomous AI agents to trade on binary prediction markets. This guide covers how to integrate AI agents with the protocol.
Overview
AI agents can autonomously:
- Monitor real-time price feeds from Pyth Network
- Analyze market positions and implied probabilities
- Execute trading strategies based on programmable logic
- Manage positions and claim settlements
Agent Skill
We provide a comprehensive trading skill that gives AI agents all the context needed to trade autonomously on Seesaw.
Skill Installation
The skill is available as a standalone markdown file that can be loaded into AI agent frameworks:
Raw Skill URL:
https://raw.githubusercontent.com/seesaw-protocol/seesaw/main/docs/sdk/seesaw-trading-skill.md
Skill Contents
The Seesaw Trading Skill provides:
| Section | Description |
|---|---|
| Protocol Overview | Binary prediction market mechanics |
| Market Lifecycle | All states from PENDING to CLOSED |
| Price Fetching | Pyth Hermes SSE streaming integration |
| Order Book Mechanics | YES/NO conversion, tick rounding |
| Trading Instructions | place_order, cancel_order, settle |
| API Endpoints | REST endpoints for market data |
| Trading Strategy Framework | Position analysis, probability estimation |
| Decision Logic | When to buy YES, buy NO, or hold |
| Fee Structure | Taker fees, maker rebates |
| Resolution Rules | How markets settle |
| PDA Derivation | Account address computation |
| Risk Management | Position limits, invariants, errors |
Loading the Skill
Claude Code / OpenClaw
Install as a local skill:
# Create skill directory
mkdir -p ~/.claude/skills/seesaw-trading
# Download skill file
curl -o ~/.claude/skills/seesaw-trading/SKILL.md \
https://raw.githubusercontent.com/seesaw-protocol/seesaw/main/docs/sdk/seesaw-trading-skill.md
Or reference directly in your agent configuration:
{
"skills": {
"seesaw-trading": {
"url": "https://raw.githubusercontent.com/seesaw-protocol/seesaw/main/docs/sdk/seesaw-trading-skill.md"
}
}
}
LangChain / LlamaIndex
Load as a document:
from langchain.document_loaders import UnstructuredMarkdownLoader
loader = UnstructuredMarkdownLoader(
"https://raw.githubusercontent.com/seesaw-protocol/seesaw/main/docs/sdk/seesaw-trading-skill.md"
)
docs = loader.load()
# Add to your agent's knowledge base
agent.add_documents(docs)
Custom Agents
Fetch and parse the skill directly:
const skillUrl =
'https://raw.githubusercontent.com/seesaw-protocol/seesaw/main/docs/sdk/seesaw-trading-skill.md';
async function loadTradingSkill(): Promise<string> {
const response = await fetch(skillUrl);
return response.text();
}
// Add to agent's system prompt or knowledge base
const skill = await loadTradingSkill();
agent.addContext(skill);
Key Capabilities
1. Real-Time Price Monitoring
Agents should connect to Pyth Hermes for streaming prices:
const PYTH_FEED_IDS = {
'BTC/USD': '0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43',
'ETH/USD': '0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace',
'SOL/USD': '0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d',
};
// SSE streaming endpoint
const streamUrl = `https://hermes.pyth.network/v2/updates/price/stream?ids[]=${feedId}&parsed=true`;
2. Market Position Analysis
Compute whether current price favors YES or NO:
interface MarketPosition {
delta: number; // currentPrice - startPrice
deltaPct: number; // Percentage change
status: 'above' | 'below' | 'at';
isAbove: boolean;
isBelow: boolean;
}
function computeMarketPosition(startPrice: number, currentPrice: number): MarketPosition {
const delta = currentPrice - startPrice;
const deltaPct = delta / startPrice;
const status = deltaPct > 0.0001 ? 'above' : deltaPct < -0.0001 ? 'below' : 'at';
return {
delta,
deltaPct,
status,
isAbove: status === 'above',
isBelow: status === 'below',
};
}
3. Trading Signal Generation
The skill includes a complete decision framework:
interface TradingSignal {
action: 'buy_yes' | 'buy_no' | 'hold';
confidence: number;
reason: string;
suggestedPrice: number;
suggestedQuantity: number;
}
// See full implementation in the skill file
function analyzeTradeOpportunity(
startPrice: number,
currentPrice: number,
marketBestBid: number,
marketBestAsk: number,
timeRemainingSeconds: number
): TradingSignal;
4. Order Execution
Build and submit orders to the Solana program:
// Order sides
enum OrderSide {
BuyYes = 0, // Bullish on price going UP
SellYes = 1,
BuyNo = 2, // Bearish on price going DOWN
SellNo = 3,
}
// Order types
enum OrderType {
Limit = 0, // Match then rest on book
PostOnly = 1, // Cancel if would match
ImmediateOrCancel = 2, // Match then cancel rest
}
Decision Framework
When to Trade
| Condition | Action | Rationale |
|---|---|---|
| Price above start, market underpricing YES | Buy YES | Capture mispricing |
| Price below start, market underpricing NO | Buy NO | Capture mispricing |
| Strong momentum up, time remaining | Buy YES | Momentum play |
| Strong momentum down, time remaining | Buy NO | Momentum play |
| No clear edge | Hold | Preserve capital |
| < 60 seconds remaining | Hold/Exit | Too risky |
Risk Considerations
| Risk | Mitigation |
|---|---|
| Position limits | Max shares per market |
| Time decay | Reduce aggression near end |
| Oracle confidence | Check confidence interval |
| Slippage | Use limit orders |
| Failed transactions | Implement retry logic |
API Integration
REST Endpoints
| Endpoint | Description |
|---|---|
GET /api/v1/markets | List all markets |
GET /api/v1/markets/current | Get active market |
GET /api/v1/markets/{id} | Market details + orderbook |
Example: Complete Trading Loop
async function agentTradingLoop() {
// 1. Get current market
const { market } = await fetch('/api/v1/markets/current').then((r) => r.json());
// 2. Get live price
const currentPrice = await fetchPythPrice(market.pythFeed);
// 3. Parse market data
const startPrice = Number(market.startPrice) * Math.pow(10, market.startPriceExpo);
const timeRemaining = new Date(market.tEnd).getTime() / 1000 - Date.now() / 1000;
// 4. Get orderbook
const { orderbook } = await fetch(`/api/v1/markets/${market.address}`).then((r) => r.json());
// 5. Generate signal
const signal = analyzeTradeOpportunity(
startPrice,
currentPrice,
orderbook.bids[0]?.price || 0,
orderbook.asks[0]?.price || 10000,
timeRemaining
);
// 6. Execute if confident
if (signal.action !== 'hold' && signal.confidence > 0.5) {
await executeOrder(market, signal);
}
}
// Run every 30 seconds
setInterval(agentTradingLoop, 30000);
Security Considerations
Agent Wallet Security
| Recommendation | Description |
|---|---|
| Dedicated wallet | Separate from main holdings |
| Limited funding | Only deposit trading capital |
| Key management | Use secure key storage |
| Transaction limits | Implement on-chain limits |
Operational Security
| Risk | Mitigation |
|---|---|
| Runaway losses | Circuit breakers, position limits |
| API key exposure | Environment variables |
| RPC manipulation | Use trusted providers |
| Strategy exploitation | Don't expose strategy details |
Monitoring
Agents should track:
- Current position (YES/NO shares held)
- P&L per market and cumulative
- Order fill rates
- Transaction success rates
- Oracle health status
Related Documentation
- Seesaw Trading Skill - Complete skill file for AI agents
- SDK Guide - TypeScript SDK documentation
- Automated Trading - General automation guide
- API Reference - REST and WebSocket APIs