Skip to main content

Automated Trading

This guide covers automated trading strategies and implementation on Seesaw.

Overview

Automated trading allows you to:

  • Execute trades based on programmatic rules
  • React faster than manual trading
  • Run consistent strategies across many markets

Architecture

Components

Data Sources

On-Chain Data

DataSourceUpdate Frequency
Market StateSolana RPCPoll or WebSocket
Order BookSolana RPCPoll or WebSocket
PositionSolana RPCAfter each trade
Oracle PricePyth~400ms

Derived Data

MetricCalculation
Mid Price(best_bid + best_ask) / 2
Spreadbest_ask - best_bid
Implied Probabilityprice / 10000
Time Remainingt_end - now

Strategy Types

1. Momentum Strategy

Trade in the direction of recent price movement:

2. Mean Reversion Strategy

Bet on prices returning to average:

3. Arbitrage Strategy

Exploit price discrepancies:

OpportunityAction
YES + NO < 10000 bpsBuy both (guaranteed profit)
YES + NO > 10000 bpsSell both (if you own them)

4. Market Making Strategy

Provide liquidity for spread capture:

See Market Making for details.

Risk Controls

Pre-Trade Checks

CheckAction if Failed
Position limitReject order
Collateral checkReject order
Market stateReject order
Time remainingReject order

Real-Time Limits

Circuit Breakers

TriggerResponse
5 failed ordersPause 30 seconds
RPC errorSwitch provider
Position limitCancel all pending
Time limitClose all positions

Order Execution

Building Transactions

1. Derive PDAs (market, orderbook, position, vault)
2. Build place_order instruction
3. Add compute budget if needed
4. Sign and send
5. Confirm and update state

Retry Logic

Priority Fees

During congestion, add priority fees:

CongestionPriority Fee
Low0
Medium10,000 microlamports
High100,000 microlamports

State Management

Position Tracking

Track after each transaction:

Position {
    yes_shares: current YES holdings
    no_shares: current NO holdings
    locked_yes: shares in sell orders
    locked_no: shares in sell orders
    pending_orders: active order IDs
    pnl: realized profit/loss
}

Order Tracking

Order {
    order_id: unique identifier
    side: BuyYes | SellYes | BuyNo | SellNo
    price: limit price in bps
    quantity: remaining shares
    status: pending | filled | cancelled
}

Monitoring

Key Metrics

MetricAlert Threshold
Fill Rate< 10% of orders filling
Latency> 2s to confirm
Position> 80% of limit
P&L> -5% of capital
Error Rate> 5% of requests

Logging

Log all:

  • Order submissions
  • Fills and partial fills
  • Cancellations
  • Errors and retries
  • Position changes

Implementation Patterns

Event Loop

Polling vs WebSocket

MethodProsCons
PollingSimple, reliableLatency, RPC load
WebSocketReal-time, efficientComplex, reconnection

Multi-Market Trading

For trading multiple markets simultaneously:

  1. Maintain separate state per market
  2. Share capital allocation
  3. Prioritize by opportunity
  4. Coordinate risk limits

Performance Optimization

Reduce Latency

OptimizationBenefit
Local RPCLower network latency
Pre-signed transactionsFaster submission
Batch updatesFewer requests
Connection poolingReuse connections

Compute Optimization

TechniqueDescription
Prefetch PDAsDerive addresses once
Cache account dataReduce RPC calls
Parallel requestsConcurrent data fetching

Testing

Backtesting

Test strategies against historical data:

  1. Collect historical order book snapshots
  2. Simulate order execution
  3. Calculate hypothetical P&L
  4. Adjust parameters

Paper Trading

Test on devnet before mainnet:

  1. Deploy to devnet
  2. Run strategy with fake funds
  3. Verify behavior matches expectations
  4. Monitor for edge cases

Production Testing

Gradual rollout:

PhaseCapitalDuration
Alpha1%1 week
Beta10%2 weeks
Production100%Ongoing

Operational Considerations

Uptime Requirements

RequirementSolution
24/7 operationCloud hosting, redundancy
FailoverMultiple instances
MonitoringAlerting system

Key Security

RiskMitigation
Key exposureEnvironment variables, vault
Transaction limitsOn-chain position limits
Unauthorized accessIP whitelisting, firewalls

Disaster Recovery

ScenarioResponse
System crashAuto-restart, state recovery
RPC failureSwitch to backup provider
Strategy malfunctionCircuit breaker, manual override

Example: Simple Trading Bot

Strategy

  1. Every 30 seconds, check Pyth oracle
  2. If price up 0.5% in last 5 min, buy YES
  3. If price down 0.5% in last 5 min, buy NO
  4. Max position: 100 shares
  5. Exit at 60 seconds before market end

Flow

Next Steps