Skip to main content

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:

SectionDescription
Protocol OverviewBinary prediction market mechanics
Market LifecycleAll states from PENDING to CLOSED
Price FetchingPyth Hermes SSE streaming integration
Order Book MechanicsYES/NO conversion, tick rounding
Trading Instructionsplace_order, cancel_order, settle
API EndpointsREST endpoints for market data
Trading Strategy FrameworkPosition analysis, probability estimation
Decision LogicWhen to buy YES, buy NO, or hold
Fee StructureTaker fees, maker rebates
Resolution RulesHow markets settle
PDA DerivationAccount address computation
Risk ManagementPosition 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

ConditionActionRationale
Price above start, market underpricing YESBuy YESCapture mispricing
Price below start, market underpricing NOBuy NOCapture mispricing
Strong momentum up, time remainingBuy YESMomentum play
Strong momentum down, time remainingBuy NOMomentum play
No clear edgeHoldPreserve capital
< 60 seconds remainingHold/ExitToo risky

Risk Considerations

RiskMitigation
Position limitsMax shares per market
Time decayReduce aggression near end
Oracle confidenceCheck confidence interval
SlippageUse limit orders
Failed transactionsImplement retry logic

API Integration

REST Endpoints

EndpointDescription
GET /api/v1/marketsList all markets
GET /api/v1/markets/currentGet 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

RecommendationDescription
Dedicated walletSeparate from main holdings
Limited fundingOnly deposit trading capital
Key managementUse secure key storage
Transaction limitsImplement on-chain limits

Operational Security

RiskMitigation
Runaway lossesCircuit breakers, position limits
API key exposureEnvironment variables
RPC manipulationUse trusted providers
Strategy exploitationDon'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