AI Agent Integration#
AI agents can trade autonomously on Seesaw binary prediction markets using the same SDK surface available to any client.
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#
The trading skill bundles all the context an AI agent needs 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/palominito/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 | Capped-linear-decay curve, three-way split, referral share |
| 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/palominito/seesaw/main/docs/sdk/seesaw-trading-skill.md
Or reference directly in your agent configuration:
{
"skills": {
"seesaw-trading": {
"url": "https://raw.githubusercontent.com/palominito/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/palominito/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/palominito/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',
};
// Browser-native EventSource cannot attach the private Pyth bearer token.
// Use an app proxy that injects PYTH_API_KEY server-side and reconnect before
// the 24-hour Pyth stream limit.
const streamUrl = `/api/pyth/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#
Explanation context. The tables below describe a simple example decision logic for illustrative purposes. Real trading strategies vary widely. The Seesaw Trading Skill contains a more complete decision framework for AI agents.
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#
Explanation context. These mitigations are design-level guidelines, not enforced constraints. Wire-level validations and on-chain invariants are described in Security.
| 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#
The endpoints most relevant to the trading loop above. For the full surface (positions, trades, fee config, WebSocket subscriptions) see the API Reference.
| 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 |
These are served by Seesaw's hosted indexer (the @seesaw/core API client
wraps them as client.api.markets.list()/current()/get()).
Indexer-Free Agents (Trustless)#
Agents that must not depend on Seesaw infrastructure — or that want the
cheapest read path against their own RPC node — can run entirely on
@seesaw/trustless: listMarkets(rpc) replaces the market
list endpoint, resolver.getOrderbook / getPosition /
getTraderBalances / findUserOrders replace the read APIs, and
resolver.resolvePlaceOrder returns every validated account a PlaceOrder
needs (including the protocol-treasury index and referral triple). Every
account is validated with the same checks the on-chain program applies, and
failures are typed errors — a property worth having when a bot signs
transactions unattended.
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; the trustless SDK validates every account so a lying node can only deny service, not corrupt a transaction |
| 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
Referral attribution for bots#
Automated agents should supply a referrer address at order-time so the 40% referral slice reaches
its intended recipient instead of forfeiting to the protocol treasury. Pass --referrer <addr> to
seesaw order place in CLI-driven bots, or supply pendingReferrer to resolveReferrer in
TypeScript agents. The resolver validates triple eligibility before attaching the trailing
accounts — a malformed triple would revert the transaction. Trustless agents get this for free:
resolvePlaceOrder returns the referral status and the exact validated triple to attach (see
the Trustless SDK guide).
// In your agent loop, resolve once per wallet session (cache the result)
const resolution = await resolveReferrer({
wallet: agentWallet,
indexerClient,
rpcClient,
pendingReferrer: process.env.SEESAW_REFERRER,
});
// Pass resolution.eligibleForTriple and resolution.address to place_order builders
See the Referral and creator fees guide for the full precedence rules and wire-level account semantics.
Related Documentation#
- Seesaw Trading Skill - Complete skill file for AI agents
- SDK Guide - TypeScript SDK documentation
- Trustless SDK - Indexer-free trading for self-custody bots
- Automated Trading - General automation guide
- API Reference - REST and WebSocket APIs
- Referral and creator fees - Fee attribution guide