Seesaw Trading Skill#
This skill provides comprehensive guidance for autonomous trading on Seesaw, a permissionless binary prediction market protocol on Solana.
Protocol Overview#
Seesaw enables trading on configurable-duration binary outcomes: will an asset's price end UP or DOWN relative to its starting price? Users trade YES/NO shares through an on-chain order book with Pyth oracle integration.
Key Characteristics#
- Configurable durations: Markets run from 60 seconds to 7 days (default: 15 minutes)
- Binary outcomes: UP (price increased or equal) or DOWN (price decreased)
- Permissionless: Anyone can trade, create markets, or run cranks
- Pyth Oracle: Exclusive use of Pyth Network for price data
- Basis points pricing: All prices in bps [0, 10000] where 10000 = 100%
Market Lifecycle#
PENDING → CREATED → TRADING → SETTLING → RESOLVED → CLOSED
Lifecycle Stages#
| Stage | Description | User Actions |
|---|---|---|
| PENDING | Market not yet created | Can call create_market |
| CREATED | Market initialized at landed time | Read createdAt and tEnd |
| TRADING | Active trading window | place_order, cancel_order |
| SETTLING | Trading ended, awaiting resolution | Wait for snapshots |
| RESOLVED | Outcome determined (UP/DOWN) | Call redeem |
| CLOSED | All positions settled | Market complete |
Time Calculations#
// docs-check: semantic
// Application helper: returns a unique positive Unix-microsecond identity that
// you persist before preparation (not part of the SDK).
declare function chooseUniquePreparationTimestampUs(): bigint;
// The two lifecycle fields read from the decoded market account.
interface MarketTimes {
createdAt: bigint;
tEnd: bigint;
}
// It selects the market PDA; it does not determine either lifecycle time.
const preparationId = chooseUniquePreparationTimestampUs();
// Read both timestamps from the landed market account after CreateMarket.
function getMarketTimes(market: MarketTimes) {
return { tStart: market.createdAt, tEnd: market.tEnd };
}
Fetching Price Data#
Pyth Network Integration#
Seesaw uses Pyth Network exclusively for price feeds. Use the Hermes SSE streaming API for real-time prices.
Known Feed IDs#
// docs-check: semantic
const PYTH_FEED_IDS = {
'BTC/USD': '0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43',
'ETH/USD': '0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace',
'SOL/USD': '0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d',
'AVAX/USD': '0x93da3352f9f1d105fdfe4971cfa80e9dd777bfc5d0f683ebb6e1294b92137bb7',
'LINK/USD': '0x8ac0c70fff57e9aefdf5edf44b51d62c2d433653cbb2cf5cc06bb115af04d221',
'ARB/USD': '0x3fa4252848f9f0a1480be62745a4629d9eb1322aebab8a791e344b3b9c1adcf5',
'OP/USD': '0x385f64d993f7b77d8182ed5003d97c60aa3361f3cecfe711544d2d59165e9bdf',
};
Streaming Real-Time Prices#
// docs-check: semantic
const STREAM_FEED_IDS = {
'BTC/USD': '0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43',
} as const;
interface PythStreamPriceUpdate {
price: {
price: string;
expo: number;
publish_time: number;
};
}
interface PythStreamMessage {
parsed?: PythStreamPriceUpdate[];
}
function buildPythStreamProxyUrl(feedId: string): string {
const url = new URL('/api/pyth/stream', 'https://api.seesaw.markets');
url.searchParams.set('ids[]', feedId);
return url.toString();
}
// Browser/EventSource paths should use a configured app proxy that injects
// PYTH_API_KEY server-side. Do not hard-code indexer REST aliases here.
const feedId = STREAM_FEED_IDS['BTC/USD'].replace(/^0x/, '');
const url = buildPythStreamProxyUrl(feedId);
const eventSource = new EventSource(url);
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data) as PythStreamMessage;
if (data.parsed && Array.isArray(data.parsed)) {
for (const update of data.parsed) {
const price = parseFloat(update.price.price);
const expo = update.price.expo;
const actualPrice = price * Math.pow(10, expo);
const publishTime = update.price.publish_time;
console.log(`Price: $${actualPrice.toFixed(2)} at ${publishTime}`);
}
}
};
One-Time Price Fetch#
// docs-check: semantic
interface HermesPriceUpdate {
price: {
price: string;
expo: number;
};
}
interface HermesLatestPriceResponse {
parsed?: HermesPriceUpdate[];
}
async function fetchCurrentPrice(feedId: string): Promise<number> {
const id = feedId.replace(/^0x/, '');
const url = `https://pyth.dourolabs.app/hermes/v2/updates/price/latest?ids[]=${id}&parsed=true`;
const response = await fetch(url, {
headers: { Authorization: `Bearer ${process.env.PYTH_API_KEY}` },
});
const data = (await response.json()) as HermesLatestPriceResponse;
if (data.parsed && data.parsed.length > 0) {
const update = data.parsed[0];
const price = parseFloat(update.price.price);
const expo = update.price.expo;
return price * Math.pow(10, expo);
}
throw new Error('No price data available');
}
Order Book Mechanics#
Understanding YES/NO Share Pricing#
Each market's order book holds two outcome lanes, YES and NO. You send
outcome, intent, and a price in that outcome's own price space. The program
stores the price unchanged and matches only inside the same outcome:
| User Intent | User Price | Stored Side | Book Arena | Stored Price | Counterparty |
|---|---|---|---|---|---|
| Buy YES @ 6000 | 6000 bps | BuyYes 1 | BID | 6000 (YES) | SellYes |
| Sell YES @ 6000 | 6000 bps | SellYes 2 | ASK | 6000 (YES) | BuyYes |
| Buy NO @ 4000 | 4000 bps | BuyNo 3 | BID | 4000 (NO) | SellNo |
| Sell NO @ 4000 | 4000 bps | SellNo 4 | ASK | 4000 (NO) | BuyNo |
Key insight: Buy NO @ 4000 locks 0.40 USDT per share and fills only against a Sell NO at 4000 or lower. It never fills against YES orders. Read the NO lane (not the YES lane) to price a NO order.
Price Interpretation#
Price in bps → Implied probability
6000 bps = 60% probability of UP
4000 bps = 40% probability of UP (or 60% probability of DOWN)
Collateral calculation:
collateral = (price_bps * quantity) / 10000
Example: Buy 100 YES shares at 6000 bps
collateral = (6000 * 100) / 10000 = 60 USDT
Tick Rounding#
Orders are rounded to tick boundaries (default: 100 bps):
- Bids: Round DOWN (buyer gets better price)
- Asks: Round UP (seller gets better price)
// docs-check: semantic
function roundToTick(price: number, tickSize: number, side: 'bid' | 'ask'): number {
if (side === 'bid') {
return Math.floor(price / tickSize) * tickSize;
} else {
const remainder = price % tickSize;
return remainder > 0 ? price + (tickSize - remainder) : price;
}
}
// Examples:
roundToTick(6050, 100, 'bid'); // → 6000
roundToTick(6050, 100, 'ask'); // → 6100
Trading Instructions#
1. Place Order#
Place a limit order on the order book.
// docs-check: semantic
import type { Address } from '@solana/addresses';
import type { OrderType, OutcomeAsset, TradeIntent } from '@seesaw/core';
interface PlaceOrderParams {
market: Address; // Market account PDA
outcome: OutcomeAsset; // 'YES' | 'NO' (wire: YES=0, NO=1)
intent: TradeIntent; // 'BUY' | 'SELL' (wire: BUY=0, SELL=1)
priceBps: number; // Named outcome's own price in bps [1, 9999]; never complemented
quantity: bigint; // Number of shares
orderType: OrderType; // 0=Limit, 1=PostOnly, 2=ImmediateOrCancel
}
Base accounts (18, before market-specific and recorder tails):
market- Market PDAorderbook- Orderbook PDAuser_position- User's position PDA (created if needed)user_token_account- User's USDT accountvault- Market vault PDAuser- User's wallet (signer)config- Protocol config PDAtreasury_token_account- Must be a config-approved recipient; the supplied recipient determines the effective treasury index- Plus: token/system programs, settlement mint, YES/NO escrows, user YES/NO ATAs, YES/NO mints, trader ledger
A spline-enabled market requires its single writable creator spline after the
base accounts. Next comes an optional single read-only ReferralAccount, then an
optional [builder_approval, builder_token_account] pair for an approved builder
(never on a PostOnly order), then the mandatory [self_program, log_authority]
recorder pair. Total: 20–23 accounts without a spline, 21–24 with one. The old three-account referral triple is not
accepted by the current native ABI.
Use the SDK builders (buildPlaceOrderIx in @seesaw/core, place_order in
the Python/Rust SDKs) with accounts your application has derived and validated.
There is no automatic self-custody account resolver; see Reading data.
2. Cancel Order#
Remove an open order from the book.
// docs-check: semantic
import type { Address } from '@solana/addresses';
interface CancelOrderParams {
market: Address;
orderId: bigint; // The order's unique u64 id (from placement or the on-chain book)
}
3. Redeem#
Claim winnings after market resolution by burning winning tokens.
// docs-check: semantic
import type { Address } from '@solana/addresses';
interface RedeemParams {
market: Address;
amount: bigint; // Amount of tokens to redeem
tokenType: 'yes' | 'no'; // Which token to redeem (0=Yes, 1=No)
}
// Payout calculation:
// if outcome == UP: burn YES tokens → receive USDT 1:1
// if outcome == DOWN: burn NO tokens → receive USDT 1:1
// if outcome == EXPIRED: burn either → receive USDT at 50%
Additional Instructions#
4. Mint Shares (0x07)#
Mint YES/NO share pairs by depositing USDT collateral.
5. Withdraw Shares (0x0A)#
Withdraw trader-ledger position shares as SPL tokens.
6. Snapshot End (0x04)#
Capture the end price snapshot after trading ends. Permissionless.
7. Resolve Market (0x05)#
Determine market outcome based on price snapshots. Permissionless.
8. Expire Market (0x06)#
Expire a market that hasn't been resolved within the expiration window.
9. Close Market (0x1B)#
Close a resolved/expired market and reclaim rent.
10. Force Close (0x18)#
Force-close a position in a resolved/expired market.
11. Create Market (0x03)#
Create a new prediction market for a given asset and duration.
12. Initialize Config (0x00)#
One-time protocol setup includes the tick size, eight protocol treasury recipient
accounts, and the default settlement mint. The taker fee coefficient and five-way
fee allocation start at protocol defaults. The authority can update them with
UpdateFeeConfig (0x1C).
13. Claim Creator Fees (0x1F)#
Permissionless sweep of deferred creator fees from the market vault to the market creator's token account.
14. Update Fee Config (0x1C)#
Admin-only. Updates the taker fee coefficient, five-way allocation, and minimum maker resting age. The five shares must sum to 10,000 bps of the collected fee.
15. Set Referrer (0x1E)#
Permissionless. Writes a ReferralAccount PDA attributing a referrer to the user. First-touch and immutable after creation; expiry only stops future referral accrual and does not allow picking a new referrer. While active, eligible taker fees accrue the configured referral share (5% at shipped defaults) as a deferred market liability when the valid referral triple is attached; rollup later credits the referrer's earnings.
16. Initialize Currency Referrer Earnings (0x4F)#
Referrer-signed. Creates the per-currency referrer earnings PDA after
InitializeCurrencyReferralTreasury (0x4E) has provisioned the selected
canonical shard for that currency; it validates that shard and never creates it lazily.
17. Claim Currency Referrer Earnings (0x50)#
Permissionless. Transfers the referrer's accumulated earnings in one currency from its bound currency referral treasury shard to the referrer's token account. Funds always go to the referrer regardless of caller.
API Endpoints#
The Seesaw indexer provides REST endpoints for market data. Use the
versioned /api/v1/ prefix.
For an indexer-free alternative — every market, order book, position, and
balance read straight from any Solana RPC node — see the
canonical v1 SDK.
List Markets#
GET /api/v1/markets?state={state}&limit={limit}&offset={offset}
Response:
{
"markets": [
{
"address": "...",
"marketId": "1234567",
"pythFeed": "...",
"state": 1,
"outcome": null,
"tStart": "2024-01-15T10:00:00Z",
"tEnd": "2024-01-15T10:15:00Z",
"startPrice": "68543210000",
"totalVolume": "1000000",
"totalTrades": 42
}
],
"total": 100,
"limit": 50,
"offset": 0
}
Get Current Market#
GET /api/v1/markets/current
Response:
{
"market": {
"id": "BTC-1H-2026-07-04T15:00Z",
"question": "Will BTC close above $110,000?"
},
"status": "trading"
}
Get Market Details#
GET /api/v1/markets/{marketId}
Response includes orderbook:
{
"market": {
"id": "BTC-1H-2026-07-04T15:00Z",
"question": "Will BTC close above $110,000?"
},
"orderbook": {
"bids": [{ "price": 6000, "quantity": "1000", "orders": 3 }],
"asks": [{ "price": 6100, "quantity": "500", "orders": 2 }]
}
}
Trading Strategy Framework#
Decision Factors#
When deciding whether to trade, consider:
- Price Position: Is current price above or below start price?
- Time Remaining: How much time until market ends?
- Momentum: Is price trending in a direction?
- Market Prices: What probabilities does the market imply?
- Confidence: How confident is the oracle price?
Computing Market Position#
// docs-check: semantic
interface MarketPosition {
delta: number; // currentPrice - startPrice
deltaPct: number; // Percentage change
status: 'above' | 'below' | 'at';
distanceToFlip: number;
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,
distanceToFlip: Math.abs(delta),
isAbove: status === 'above',
isBelow: status === 'below',
};
}
const samplePosition = computeMarketPosition(100, 101);
console.log(samplePosition.status, samplePosition.distanceToFlip);
Implied Probability Heuristic#
// docs-check: semantic
interface MarketPosition {
delta: number;
deltaPct: number;
status: 'above' | 'below' | 'at';
distanceToFlip: number;
isAbove: boolean;
isBelow: boolean;
}
function computeImpliedProbability(
position: MarketPosition,
volatilityFactor: number = 0.02
): number {
// Logistic function centered at start price
const k = 1 / volatilityFactor;
const probability = 1 / (1 + Math.exp(-k * position.deltaPct));
return Math.max(0.01, Math.min(0.99, probability));
}
const probability = computeImpliedProbability({
delta: 1,
deltaPct: 0.01,
status: 'above',
distanceToFlip: 1,
isAbove: true,
isBelow: false,
});
console.log(probability);
Trading Decision Logic#
// docs-check: semantic
interface MarketPosition {
delta: number;
deltaPct: number;
status: 'above' | 'below' | 'at';
distanceToFlip: number;
isAbove: boolean;
isBelow: boolean;
}
interface TradingSignal {
action: 'buy_yes' | 'buy_no' | 'hold';
confidence: number;
reason: string;
suggestedPrice: number;
suggestedQuantity: number;
}
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,
distanceToFlip: Math.abs(delta),
isAbove: status === 'above',
isBelow: status === 'below',
};
}
function computeImpliedProbability(
position: MarketPosition,
volatilityFactor: number = 0.02
): number {
const k = 1 / volatilityFactor;
const probability = 1 / (1 + Math.exp(-k * position.deltaPct));
return Math.max(0.01, Math.min(0.99, probability));
}
function analyzeTradeOpportunity(
startPrice: number,
currentPrice: number,
marketBestBid: number, // Best YES-lane bid in YES bps
marketBestAsk: number, // Best YES-lane ask in YES bps
marketBestNoAsk: number, // Best NO-lane ask in NO bps
timeRemainingSeconds: number,
volatilityEstimate: number = 0.02
): TradingSignal {
const position = computeMarketPosition(startPrice, currentPrice);
const impliedProb = computeImpliedProbability(position, volatilityEstimate);
// Convert to basis points
const impliedPriceBps = Math.round(impliedProb * 10000);
// Market mid price
const marketMid = (marketBestBid + marketBestAsk) / 2;
// Look for mispricing
const priceDiff = impliedPriceBps - marketMid;
const threshold = 200; // 2% edge threshold
// Time decay factor - less aggressive near end
const timeFactor = Math.max(0.3, timeRemainingSeconds / 900);
if (priceDiff > threshold * timeFactor) {
// Market underpricing YES (or overpricing NO)
// Buy YES below our fair value
return {
action: 'buy_yes',
confidence: Math.min(1, Math.abs(priceDiff) / 500),
reason: `YES underpriced by ${priceDiff} bps`,
suggestedPrice: Math.min(impliedPriceBps - 50, marketBestAsk),
suggestedQuantity: calculatePositionSize(priceDiff, timeFactor),
};
} else if (priceDiff < -threshold * timeFactor) {
// Market overpricing YES (or underpricing NO)
// Buy NO
return {
action: 'buy_no',
confidence: Math.min(1, Math.abs(priceDiff) / 500),
reason: `NO underpriced by ${-priceDiff} bps`,
// Our model's fair NO value is 10000 - impliedPriceBps. The order is a
// NO bid priced in NO bps against the NO lane; it is never converted.
suggestedPrice: Math.min(10000 - impliedPriceBps - 50, marketBestNoAsk),
suggestedQuantity: calculatePositionSize(-priceDiff, timeFactor),
};
}
return {
action: 'hold',
confidence: 0,
reason: 'No significant mispricing detected',
suggestedPrice: 0,
suggestedQuantity: 0,
};
}
function calculatePositionSize(edgeBps: number, timeFactor: number): number {
// Kelly-inspired sizing: bet more when edge is larger
// Scale down near market end (timeFactor)
const baseSize = 100; // Base position in shares
const edgeFactor = Math.min(3, Math.abs(edgeBps) / 100);
return Math.floor(baseSize * edgeFactor * timeFactor);
}
const signal = analyzeTradeOpportunity(100, 101, 5_800, 6_100, 4_100, 600);
console.log(signal.action, signal.suggestedQuantity);
Fee Structure#
Seesaw uses a linear taker fee that decreases with the fill price in the taker's outcome lane. Eligible maker fills earn a separately floored rebate; ineligible maker allocation and rounding dust go to protocol, as does the referral allocation without an eligible referrer. The shipped allocation is 45% protocol / 5% creator / 5% referral / 5% approved builder / 40% eligible maker rebate; an unpaid builder allocation stays with protocol. See fee constants and allocation details.
<!-- src: program/src/logic/fee.rs:187 FeeSplit5::TARGET -->fee = ceil(notional × taker_fee_coefficient_bps × (10_000 − price_bps) / 100_000_000)
The default taker_fee_coefficient_bps is 400. Read deployed config for the
current value. The fee rounds up once from the exact fraction.
| Fill price | Effective taker fee |
|---|---|
| 0.10 | 3.60% |
| 0.50 | 2.00% |
| 0.80 | 0.80% |
| 0.90 | 0.40% |
| 0.95 | 0.20% |
| 0.99 | 0.04% |
Five-Way Allocation#
Configured shares are bps of fee and sum to 10_000:
- Protocol treasury: 45% (4_500 bps of fee)
- Market creator: 5% (500 bps of fee)
- Referral allocation: 5% (500 bps of fee) — deferred for an eligible referrer, else protocol
- Builder allocation: 5% (500 bps of fee) — paid to an approved builder named on the order, capped by the trader's approval, else protocol
- Maker allocation: 40% (4_000 bps of fee) — free quote balance on eligible fills, else protocol
// docs-check: semantic
import { applySplit, computeTakerFee, DEFAULT_FEE_SPLIT } from '@seesaw/core';
function calculateFees(
notional: bigint,
priceBps: number,
isTaker: boolean,
hasReferrer: boolean,
takerFeeCoefficientBps: number = 400
): {
total: bigint;
protocolFee: bigint;
creatorFee: bigint;
referralFee: bigint;
} {
if (!isTaker) {
return { total: 0n, protocolFee: 0n, creatorFee: 0n, referralFee: 0n };
}
// Single-fill illustration with no eligible maker rebate (makerTotal = 0n).
// Pass actual credited maker totals for eligible fills; unused maker share
// remains with protocol. Multi-fill fees must be calculated per fill.
// Matches on-chain rounding: total fee rounds up, creator/referral shares
// round down, and all dust stays with protocol. No builder is named here
// (effective builder bps 0), so the builder share stays with protocol.
const total = computeTakerFee(notional, priceBps, takerFeeCoefficientBps);
const split = applySplit(total, DEFAULT_FEE_SPLIT, 0n);
// If taker has no eligible referrer, the referral share flows to protocol.
const protocolFee = hasReferrer ? split.protocol : split.protocol + split.referral;
const referralFee = hasReferrer ? split.referral : 0n;
return {
total: split.total,
protocolFee,
creatorFee: split.creator,
referralFee,
};
}
Resolution Rules#
Sampling Rule A#
P_start= Authenticated positive Pyth update supplied during creation; its publish time must be no more than 60 seconds old at the landed Clock time and may precedet_startP_end= First Pyth price wherepublish_time >= t_end
Outcome Determination#
start_interval = [start_low, start_high]
end_interval = [end_low, end_high]
if end_low > start_high:
outcome = UP
elif end_high < start_low:
outcome = DOWN
else:
outcome = EXPIRED
Important: equality, touching, overlap, and missing or unusable snapshots
are neutral EXPIRED; the point-price jump guard is separate.
Payout Calculation#
PDA Derivation#
// docs-check: semantic
import { address } from '@solana/addresses';
import {
deriveMarketPda,
deriveOrderbookPda,
deriveVaultPda,
derivePositionPda,
deriveConfigPda,
deriveAssetPda,
deriveYesMintPda,
deriveNoMintPda,
} from '@seesaw/core';
const pythFeedId = new Uint8Array(32);
const durationSeconds = 900n;
const marketId = 1n;
const creatorAddress = address('11111111111111111111111111111111');
const userAddress = address('SysvarC1ock11111111111111111111111111111111');
// Market PDA uses 7 seeds; the registered currency record is the last one:
// ["seesaw", "market", pyth_feed_id(32), duration_seconds(8 LE), preparation id(8 LE), creator(32), currency_record(32)]
const currencyRecord = address('SysvarRent111111111111111111111111111111111'); // deriveCurrencyRecordPda(mint, tokenProgram)
const [marketPda] = await deriveMarketPda(
pythFeedId,
durationSeconds,
marketId,
creatorAddress,
currencyRecord
);
const [orderbookPda] = await deriveOrderbookPda(marketPda);
const [vaultPda] = await deriveVaultPda(marketPda);
const [positionPda] = await derivePositionPda(marketPda, userAddress);
// Additional PDA derivations
const [configPda] = await deriveConfigPda();
const [assetPda] = await deriveAssetPda(pythFeedId);
const [yesMintPda] = await deriveYesMintPda(marketPda);
const [noMintPda] = await deriveNoMintPda(marketPda);
console.log({ orderbookPda, vaultPda, positionPda, configPda, assetPda, yesMintPda, noMintPda });
Risk Management#
Position Limits#
max_order_sizedefaults to 1,000,000,000,000 share atoms. This is 1,000,000 shares for a six-decimal market. The authority can change it withUpdateOperationalParams(0x2A).- No per-user order limit: an earlier
max_orders_per_userfield was retired and is no longer enforced - Each canonical order book has two arenas of 4,096 order slots each.
Key Invariants (Never Violated)#
- Solvency:
vault >= max(total_yes_shares, total_no_shares) + accumulated_creator_fees - Conservation: Every trade conserves value (collateral in = shares out)
- No Negative Exposure: All share balances >= 0
- No Crossed Book:
best_bid < best_askwhen both exist
Error Handling#
Common errors to handle:
Errors are a custom #[repr(u32)] SeesawError enum (category-prefixed hex codes, NOT
Anchor 6000+). Representative codes:
| Error Code | Name | Meaning |
|---|---|---|
| 0x1002 | InvalidState | Market not in the expected state |
| 0x1005 | AlreadyResolved | Market already resolved |
| 0x2002 | StaleOracle | Oracle price too old |
| 0x3001 | InvalidQuantity | Order quantity invalid |
| 0x3004 | WouldCross | PostOnly order would cross book |
| 0x3007 | SlippageExceeded | Fill price outside tolerance |
| 0x4001 | MathOverflow | Arithmetic overflow |
| 0x6001 | ProtocolPaused | Protocol is paused |
Complete Trading Flow Example#
// docs-check: semantic
interface TradingFlowMarket {
address: string;
pythFeed: string;
startPrice: string;
startPriceExpo: number;
tEnd: string;
}
interface TradingFlowLane {
bestBid: number | null;
bestAsk: number | null;
}
interface TradingFlowOrderbook {
// Per-outcome lanes; each lane's prices are in that outcome's own bps.
lanes: { yes: TradingFlowLane; no: TradingFlowLane };
}
interface TradingSignal {
action: 'buy_yes' | 'buy_no' | 'hold';
confidence: number;
reason: string;
suggestedPrice: number;
suggestedQuantity: number;
}
interface PythLatestPriceResponse {
parsed: Array<{
price: {
price: string;
expo: number;
};
}>;
}
function analyzeTradeOpportunity(
startPrice: number,
currentPrice: number,
yesLane: TradingFlowLane,
noLane: TradingFlowLane,
timeRemainingSeconds: number
): TradingSignal {
const buyYes = currentPrice >= startPrice;
// Price each order from its own outcome's lane, in that outcome's bps.
const lane = buyYes ? yesLane : noLane;
const midpoint = Math.floor(((lane.bestBid ?? 0) + (lane.bestAsk ?? 10000)) / 2);
if (timeRemainingSeconds < 60) {
return {
action: 'hold',
confidence: 0.2,
reason: 'market is near expiry',
suggestedPrice: midpoint,
suggestedQuantity: 0,
};
}
return {
action: buyYes ? 'buy_yes' : 'buy_no',
confidence: 0.6,
reason: buyYes ? 'current price is above start' : 'current price is below start',
suggestedPrice: midpoint,
suggestedQuantity: 1_000_000,
};
}
async function executeTradingStrategy() {
// 1. Get current market
const marketResponse = await fetch('/api/v1/markets/current');
const { market, status } = (await marketResponse.json()) as {
market: TradingFlowMarket;
status: string;
};
if (status !== 'trading') {
console.log('No active market, waiting...');
return;
}
// 2. Stream live price
const feedId = market.pythFeed.replace(/^0x/, '');
const priceUrl = `https://pyth.dourolabs.app/hermes/v2/updates/price/latest?ids[]=${feedId}&parsed=true`;
const priceResponse = await fetch(priceUrl, {
headers: { Authorization: `Bearer ${process.env.PYTH_API_KEY}` },
});
const priceData = (await priceResponse.json()) as PythLatestPriceResponse;
const currentPrice =
parseFloat(priceData.parsed[0].price.price) * Math.pow(10, priceData.parsed[0].price.expo);
// 3. Parse market data
const startPrice = Number(market.startPrice) * Math.pow(10, market.startPriceExpo);
const tEnd = new Date(market.tEnd).getTime() / 1000;
const now = Date.now() / 1000;
const timeRemaining = tEnd - now;
// 4. Get orderbook
const obResponse = await fetch(`/api/v1/markets/${market.address}`);
const { orderbook } = (await obResponse.json()) as { orderbook: TradingFlowOrderbook };
// 5. Analyze opportunity (YES and NO lanes are separate books)
const signal = analyzeTradeOpportunity(
startPrice,
currentPrice,
orderbook.lanes.yes,
orderbook.lanes.no,
timeRemaining
);
console.log('Trading signal:', signal);
// 6. Execute if confident
if (signal.action !== 'hold' && signal.confidence > 0.5) {
// Build and send transaction...
console.log(`Executing: ${signal.action} at ${signal.suggestedPrice} bps`);
}
}
// Run every 30 seconds during active markets
const strategyTimer = setInterval(() => void executeTradingStrategy(), 30_000);
clearInterval(strategyTimer);
Instruction Discriminators#
| Discriminator | Instruction | Description |
|---|---|---|
| 0x00 | InitializeConfig | One-time protocol setup |
| 0x01 | UpdateAuthority | Name pending protocol authority |
| 0x02 | ClaimAuthority | Pending authority accepts control |
| 0x03 | CreateMarket | Create a new prediction market |
| 0x04 | SnapshotEnd | Capture end price after trading window |
| 0x05 | ResolveMarket | Determine outcome from price snapshots |
| 0x06 | ExpireMarket | Late-resolve or expire after timeout |
| 0x07 | MintShares | Mint YES and NO share pairs from settlement funds |
| 0x08 | DepositFunds | Deposit settlement tokens into the trader ledger |
| 0x09 | WithdrawFunds | Withdraw settlement tokens from the trader ledger |
| 0x0A | WithdrawShares | Withdraw shares as SPL tokens |
| 0x0B | MergeCompleteSet | Burn a YES+NO pair back into settlement funds |
| 0x0C | PlaceOrder | Place order on the order book |
| 0x0D | PlaceMultiplePostOnly | Batch post-only placement |
| 0x0E | SwapWithFreeFunds | IOC trade using ledger free funds |
| 0x0F | PlaceLimitWithFreeFunds | Limit/PostOnly using ledger free funds |
| 0x10 | BatchPostOnlyWithFreeFunds | Batch post-only using ledger free funds |
| 0x11 | CancelOrder | Cancel an open order |
| 0x12 | CancelMultipleOrdersById | Bulk cancel explicit order IDs |
| 0x13 | ReduceOrder | Reduce a resting order |
| 0x14 | CancelMultipleOrdersByIdWithFreeFunds | Bulk cancel to ledger free funds |
| 0x15 | ReduceOrderWithFreeFunds | Reduce order to ledger free funds |
| 0x16 | ReclaimExpiredOrder | Reclaim expired resting order |
| 0x17 | Redeem | Burn outcome tokens for their settlement payout |
| 0x18 | ForceClose | Force-close expired position |
| 0x19 | MarkPositionSettled | Mark empty position settled |
| 0x1A | ClosePosition | Close settled position PDA |
| 0x1B | CloseMarket | Close market and reclaim rent |
| 0x1C | UpdateFeeConfig | Update the fee coefficient, allocation, and maker resting age |
| 0x1D | UpdateTreasuryRecipients | Rotate all 8 protocol treasury recipients |
| 0x1E | SetReferrer | Attribute a referrer to a user |
| 0x1F | ClaimCreatorFees | Sweep deferred creator fees |
| 0x20 | Pause | Pause protocol trading |
| 0x21 | Unpause | Resume protocol trading |
| 0x22 | EnablePostOnlyMode | Enable protocol-wide PostOnly mode |
| 0x23 | DisablePostOnlyMode | Disable protocol-wide PostOnly mode |
| 0x24 | UpdateTickSize | Update order-book tick size |
| 0x25 | UpdateMinRestingNotional | Update minimum resting notional |
| 0x26 | UpdateMarketCap | Update market max total shares |
| 0x27 | SetMarketEmergencyStatus | Rotate market emergency status |
| 0x28 | ForceCancelMarketOrders | Admin force-cancel market order |
| 0x29 | SetPauser | Configure escalation-only pauser authority |
| 0x2A | UpdateOperationalParams | Tune post-deploy operational parameters |
| 0x2B | EnsureTraderLedgerSpace | Prepare space for the canonical trader ledger |
| 0x2C | EnsureDeepOrderbookSpace | Prepare space for the canonical order book |
| 0x2D | TopUpCloserRewards | Fund closer reward budget shortfall |
| 0x2E | InitSplineSeries | Create a market maker’s spline series |
| 0x2F | UpdateSeriesTemplate | Update a spline series template |
| 0x30 | UpdateSeatQuote | Publish a seat quote (pause, quote or quote with tick window) |
| 0x31 | AttachSeat | Attach a maker’s spline seat to a market |
| 0x32 | SettleSeat | Settle a spline seat after market resolution |
| 0x33 | RecoverSeat | Recover eligible capital from a spline seat |
| 0x34 | DepositSeriesVault | Fund a spline series vault |
| 0x35 | WithdrawSeriesVault | Withdraw available funds from a spline series vault |
| 0x36 | CloseSplineSeries | Close an eligible spline series |
| 0x37 | BeginSourceMarket | Prepare a signed-source market and its receipt |
| 0x38 | OpenSourceMarket | Open a prepared market using a signed source result |
| 0x39 | ExpireExternalMarket | Permissionlessly expire an unresolved external market |
| 0x3A | ClosePreallocatedChild | Close an abandoned native child (creator); eventless |
| 0x3B | ReclaimExternalMarketPreallocation | Return unconsumed preparation to receipt creator |
| 0x3C | TopUpExternalProgressReserve | Restore unpaid lifecycle-progress reserve; eventless |
| 0x3D | EvacuateIdleSeat | Evacuate an idle trader-ledger seat |
| 0x3E | ResolveSourceMarket | Accept a signed source resolution observation |
| 0x3F | HaltSourceMarket | Accept a signed source halt result |
| 0x40 | UpdateSourceClose | Accept a signed source close-time update |
| 0x41 | FinalizeSourceMarket | Finalize an eligible source market after review |
| 0x42 | CloseSourceAccounts | Close eligible accounts for a terminal source market |
| 0x43 | InitializeSourceControl | Initialize signed-source profile governance |
| 0x44 | SetSourceProfilePolicy | Set the admission policy for a source profile |
| 0x45 | InitializeWitnessRegistry | Initialize the witness registry |
| 0x46 | RevokeWitnessSlot | Revoke a witness registry slot |
| 0x47 | SetWitnessMeasurement | Set policy for an enclave image measurement |
| 0x48 | RegisterAttestedWitness | Register a witness using an attestation proof |
| 0x49 | RotateSeatQuoteAuthority | Rotate the authority allowed to publish seat quotes |
| 0x4A | ApproveBuilder | Approve a builder to share the trader's taker fees |
| 0x4B | RevokeBuilder | Revoke a builder approval and refund its rent |
| 0x4C | SetCurrencyFreezeException | Initialize, approve, or revoke a freeze exception |
| 0x4D | RegisterCurrency | Permissionlessly record an authenticated mint |
| 0x4E | InitializeCurrencyReferralTreasury | Create a per-currency referral treasury shard |
| 0x4F | InitializeCurrencyReferrerEarnings | Create a per-currency referrer earnings account |
| 0x50 | ClaimCurrencyReferrerEarnings | Claim referrer earnings in a registered currency |
| 0x51 | RollupCurrencyReferralFees | Roll referral liabilities into currency earnings |
| 0x52 | InitializeCurrencyProtocolTreasury | Create a per-currency protocol treasury shard |
| 0x53 | WithdrawCurrencyProtocolTreasury | Withdraw a currency protocol shard (config authority) |
| 0x54 | CancelOrderByClientId | Cancel an owner’s order by its client identifier |
| 0x55 | CancelOwnerOrders | Advance a bounded owner cancellation session |
| 0x56 | ConfigureStrategy | Create or update an owner-authorized strategy |
| 0x57 | StopStrategy | Stop a strategy and disable its resting orders at execution |
| 0x58 | ResumeStrategy | Resume an eligible stopped strategy |
| 0x59 | CloseStrategy | Close an eligible strategy account |
| 0x5A | ResetStrategyCapital | Reset strategy capital accounting when permitted |
| 0x5B | UpdateSeatTables | Update the levels of an attached spline seat |
| 0x5C | TopUpSeatCommitment | Add capital to a spline seat commitment |
| 0x5D | AttachSeatFromSeries | Attach a seat under a series subscription |
| 0x5E | UpdateSeriesSubscription | Set a series subscription’s attachment terms |
| 0x5F | TopUpSeriesLamports | Fund a spline series’ lamport budget |
| 0x60 | FlagSeatBelowFloor | Record that a seat is below its commitment floor |
| 0x61 | MakeSeatDormant | Make an eligible underfunded seat dormant |
| 0x62 | CloseSeat | Close an eligible spline seat |
| 0x63 | AssertBalances | Check final wallet or trader-ledger balance bounds |
| 0x64 | ReplaceMakerQuotes | Replace managed maker quotes in the order book |
| 0x65 | SetMakerQuoteAuthority | Set a managed quote publisher’s authority |
| 0x66 | InitializeMakerQuoteState | Initialize managed maker quote state |
| 0x67 | CloseMakerQuoteState | Close eligible managed maker quote state |
| 0x68 | FundMakerQuoteInventory | Fund managed maker quote inventory |
| 0x69 | WithdrawMakerQuoteInventory | Withdraw available managed quote inventory |
| 0x6A | ReclaimExpiredOrders | Reclaim expired managed maker orders in a bounded batch |
| 0x6B | CreateConfidentialMarket | Create a version 1 confidential market with a Pyth opening |
| 0x6C | RecordConfidentialTerminal | Record the confidential market outcome or timeout refund |
| 0x6D | ClaimOwnerPayoutEscrow | Withdraw an owner payout escrow to the owner's token account |
| 0x6E | UpdateSeatParams | Replace a seat's quote-program params |
| 0x6F | UpdateSeatProgram | Install a quote program on an attached seat |
| 0x70 | OpenConfidentialJob | Open a confidential execution job |
| 0x71 | AppendConfidentialJobPage | Append a page to an open confidential job |
| 0x72 | SealConfidentialJob | Seal a confidential job for execution |
| 0x73 | CommitConfidentialJob | Commit a sealed confidential job |
| 0x74 | AbortConfidentialJob | Abort an uncommitted confidential job |
| 0x75 | TopUpConfidentialWorkBudget | Top up a confidential work budget |
| 0x76 | IncreaseConfidentialCap | Increase a confidential market's supply cap |
| 0x77 | CloseConfidentialMarket | Close an eligible confidential market |
| 0x78 | FundConfidentialEscrow | Fund a confidential escrow account |
| 0x79 | PrepareConfidentialStep | Prepare a confidential execution step |
| 0x7A | RefundConfidentialObject | Refund a confidential object |
| 0x7B | CreateConfidentialClaims | Create confidential settlement claims |
| 0x7C | MaterializeConfidentialClaim | Materialize a confidential claim |
| 0x7D | RefundConfidentialClaim | Refund an unmaterialized confidential claim |
| 0x7E | UploadConfidentialCapsule | Upload a confidential capsule payload |
| 0x7F | ReclaimConfidentialCapsuleSlot | Reclaim an expired confidential capsule slot |
| 0x80 | ActivateConfidentialRfq | Activate a confidential RFQ fill |
| 0x81 | SettleConfidentialCell | Settle a confidential position cell |
| 0x82 | SettleConfidentialPublicCell | Settle a confidential public cell |
| 0x83 | ClaimConfidentialRole | Claim a confidential cell role payout |
| 0x84 | CloseConfidentialCellByAgreement | Close a confidential cell by mutual agreement |
| 0x85 | NovateConfidentialCell | Novate a confidential cell to a new counterparty |
| 0x86 | AssignConfidentialCell | Assign a confidential cell to another owner |
| 0x87 | ReassignConfidentialClaim | Reassign a confidential claim |
| 0x88 | RekeyConfidentialCell | Rekey a confidential cell |
| 0x89 | PostConfidentialRemainingOrder | Post remaining size of a confidential order |
| 0x8A | FillConfidentialOrder | Fill a posted confidential order |
| 0x8B | RefundConfidentialRemainder | Refund the unfilled remainder of a confidential order |
| 0x8C | SplitConfidentialCountedRun | Split a confidential counted run |
| 0x8D | ReplaceConfidentialCellDyadic | Replace a confidential cell with a dyadic split |
| 0x8E | SplitConfidentialCell | Split a confidential cell |
| 0x8F | RekeyConfidentialSplitRole | Rekey a confidential split role |
| 0x90 | MergeConfidentialCells | Merge confidential cells |
| 0x91 | CertifyConfidentialClosure | Certify closure of a confidential market |
| 0x92 | ReclaimConfidentialStorage | Reclaim closed confidential storage accounts |
| 0x93 | CommitConfidentialOrder | Commit a confidential batch order |
| 0x94 | CancelConfidentialOrder | Cancel a committed confidential order |
| 0x95 | SealConfidentialEpochCutoff | Seal the cutoff for a confidential batch epoch |
| 0x96 | RevealConfidentialOrder | Reveal a committed confidential order |
| 0x97 | ActivateConfidentialStanding | Activate a confidential standing order |
| 0x98 | FinalizeConfidentialEpoch | Finalize a confidential batch epoch |
| 0x99 | SubmitConfidentialClearingPage | Submit a confidential epoch clearing page |
| 0x9A | VerifyConfidentialPlan | Verify a confidential clearing plan |
| 0x9B | ExecuteConfidentialBatchAtomic | Execute a confidential batch atomically |
| 0x9C | CompleteConfidentialBatch | Complete a confidential batch execution |
| 0x9D | CommitConfidentialStanding | Commit a confidential standing order |
| 0x9E | CancelConfidentialStanding | Cancel a confidential standing order |
| 0x9F | ReleaseConfidentialStanding | Release a confidential standing order |
| 0xA0 | AmendConfidentialStanding | Amend a confidential standing order |
| 0xA1 | LockConfidentialSource | Lock a confidential source state |
| 0xA2 | NormalizeConfidentialSource | Normalize a confidential source state |
| 0xA3 | ReleaseConfidentialSourceLock | Release a confidential source lock |
| 0xA4 | CreateShieldedOutcomeMints | Create shielded outcome token mints |
| 0xA5 | MintShieldedPair | Mint a shielded YES/NO token pair |
| 0xA6 | MergeShieldedSet | Merge a shielded YES/NO token pair |
| 0xA7 | RedeemShieldedTerminal | Redeem shielded outcome tokens after resolution |
| 0xA8 | BridgeConfidentialCellToTokens | Bridge a confidential cell to shielded outcome tokens |
| 0xA9 | BridgeTokensToConfidentialCell | Bridge shielded outcome tokens to a confidential cell |
| 0xAA | OpenConfidentialRoute | Open a confidential multi-leg route |
| 0xAB | RefundConfidentialRouteLeg | Refund a leg of a confidential route |
| 0xAC | ActivateConfidentialFinancedCell | Activate a confidential financed cell |
| 0xAD | RepayConfidentialFinancing | Repay financing on a confidential cell |
| 0xAE | SettleConfidentialFinancedRole | Settle a financed role in a confidential cell |
| 0xAF | ExchangeConfidentialCellPartForTokens | Exchange a confidential cell part for shielded tokens |
| 0xB0 | ExchangeTokensForConfidentialCellPart | Exchange shielded tokens for a confidential cell part |
| 0xB1 | AdmitContinuousAction | Admit an action to the continuous confidential queue |
| 0xB2 | ProcessContinuousAction | Process an admitted continuous confidential action |
| 0xB3 | FillContinuousStep | Fill a continuous confidential matching step |
| 0xB4 | TriggerContinuousRecoveryBarrier | Trigger the continuous confidential recovery barrier |
| 0xB5 | PublishSplineOffer | Publish a confidential spline offer |
| 0xB6 | FillSplineOffer | Fill a confidential spline offer |
| 0xB7 | ExpireSplineOffer | Expire a confidential spline offer |
| 0xB8 | GrantSplineDelegate | Grant a confidential spline delegate |
| 0xB9 | RevokeSplineDelegate | Revoke a confidential spline delegate |
| 0xBA | VerifyContinuousTreeParity | Verify continuous confidential tree parity |
| 0xBB | RebuildContinuousTree | Rebuild a continuous confidential tree |
| 0xBC | DepositConfidentialReservePool | Deposit into a confidential reserve pool |
| 0xBD | WithdrawConfidentialReservePool | Withdraw from a confidential reserve pool |
| 0xBE | RefreshReservePoolOffer | Refresh a confidential reserve pool offer |
The public ABI has 191 contiguous routes, 0x00 through 0xBE, declared once
in program/src/abi_compaction.rs::ROUTES; no instruction byte is reserved or
tombstoned. Every byte from 0xBF through 0xFE is rejected with
InvalidInstructionData before account access.
Internal LOG (0xFF) is excluded. Recorder-tail requirements are route-specific;
use the generated manifest and
account-list conventions.
Quick Reference#
When to Trade#
BUY YES when:
- Price is above start AND market underpricing YES
- Strong upward momentum with time remaining
- Market ask price < your fair value estimate
BUY NO when:
- Price is below start AND market underpricing NO
- Strong downward momentum with time remaining
- Market bid price > your fair value estimate
HOLD when:
- No significant mispricing
- Very little time remaining (< 1 minute)
- High oracle confidence interval
- Already at position limits