Skip to main content

Fetching market data

This guide covers how to fetch and work with market data using the Context SDK.

Setup

import { ContextClient } from "@contextwtf/sdk"

const ctx = new ContextClient()
No API key needed — all market data is publicly accessible.

Getting market lists

Fetch the hottest markets by recent trading volume:
const { markets } = await ctx.markets.list({
  sortBy: "trending",
  limit: 10,
})

for (const market of markets) {
  console.log(`- ${market.question}`)
}

Filtering markets

Find markets matching specific criteria:
const { markets } = await ctx.markets.list({
  query: "bitcoin",       // search by question text
  status: "active",       // active | pending | resolved | closed
  sortBy: "trending",     // new | volume | trending | ending | chance
  sort: "desc",           // asc | desc
  category: "crypto",     // filter by category
  creator: "0x...",       // filter by creator address
  visibility: "visible",  // visible | hidden | all
  limit: 20,
})

Paginating results

Handle large result sets with cursor-based pagination:
let cursor: string | undefined

do {
  const res = await ctx.markets.list({
    sortBy: "new",
    limit: 50,
    cursor,
  })

  for (const market of res.markets) {
    console.log(market.question)
  }

  cursor = res.cursor ?? undefined
} while (cursor)

Getting market details

Single market

// By hex ID
const market = await ctx.markets.get("0x1234...")

// By slug
const market = await ctx.markets.get("will-bitcoin-hit-100k")

console.log(market.question)
console.log(market.status)         // "active" | "pending" | "resolved" | "closed"
console.log(market.metadata.slug)

Getting quotes

Get current bid/ask prices for a market:
const quotes = await ctx.markets.quotes("0x1234...")

if (quotes.yes.bid && quotes.yes.ask) {
  console.log(`Yes: ${quotes.yes.bid}¢ bid / ${quotes.yes.ask}¢ ask`)
  console.log(`Spread: ${quotes.spread}¢`)
}

Working with orderbooks

Snapshot

Get the current orderbook state:
const book = await ctx.markets.orderbook("0x1234...", { depth: 20 })

console.log("Best bid:", book.bids[0]?.price, "¢")
console.log("Best ask:", book.asks[0]?.price, "¢")
Prices are in cents (0-100). Size is in number of contracts.

Real-time streaming

For real-time orderbook updates, use Server-Sent Events by setting the Accept header:
const eventSource = new EventSource(
  "https://api-testnet.context.markets/v2/markets/0x1234.../orderbook?depth=10",
)

eventSource.addEventListener("snapshot", (e) => {
  const book = JSON.parse(e.data)
  console.log("Initial book:", book)
})

eventSource.addEventListener("price_change", (e) => {
  const change = JSON.parse(e.data)
  console.log("Price update:", change)
})

eventSource.addEventListener("last_trade", (e) => {
  const trade = JSON.parse(e.data)
  console.log("Trade:", trade)
})
See the API reference for the full SSE event specification.

Calculate spread

const book = await ctx.markets.orderbook("0x1234...")

if (book.bids.length && book.asks.length) {
  const bestBid = book.bids[0].price
  const bestAsk = book.asks[0].price
  const spread = bestAsk - bestBid
  const midPrice = (bestBid + bestAsk) / 2

  console.log(`Spread: ${spread}¢ (${((spread / midPrice) * 100).toFixed(1)}%)`)
}

Price history

Fetch historical prices

const history = await ctx.markets.priceHistory("0x1234...", {
  timeframe: "1w",
})

console.log(`${history.prices.length} data points`)

for (const point of history.prices) {
  const date = new Date(point.time * 1000)
  console.log(`${date.toISOString()}: ${point.price}¢`)
}
Available timeframes: "1h", "6h", "1d", "1w", "1M", "all".

Market activity

Recent trades

const { activity } = await ctx.markets.activity("0x1234...", {
  types: "trade",
  limit: 50,
})

for (const item of activity) {
  console.log(`${item.timestamp}: ${item.type}`)
}

Global activity feed

const { activity } = await ctx.markets.globalActivity({ limit: 20 })

Simulating trades

Preview expected execution before placing a real order:
const sim = await ctx.markets.simulate("0x1234...", {
  side: "yes",
  amount: 100,
  amountType: "usd",
})

console.log(`Would buy ${sim.estimatedContracts} contracts at ${sim.estimatedAvgPrice}¢`)
console.log(`Slippage: ${sim.estimatedSlippage.toFixed(2)}%`)

What’s next?