Docs   v0 · paper trading

Prophet docs

Everything in one place: get started, run it yourself, ask in plain English, connect your own agent, and the full reference.

On this page Overview How it works Ground rules Venues and grades Quickstart Install Create an API key Start the servers Stop the servers Configuration Deploy Updating Plain English Console desk Example script MCP clients Good things to ask Authentication MCP REST Search and browse The market graph Market detail and comparison Intents Plans Execute Track and cancel Views Entry and exit analysis Exit plans Portfolio and limits Position sizing Operations Agents API Tools Endpoints Errors Risk and exclusion codes Troubleshooting FAQ For contributors
Introduction

Overview

Prophet is an API and MCP server for agents that trade prediction markets. Your agent states an intent, for example "buy $100 of YES, but only if my edge is at least 3%". Prophet returns an auditable, fee-aware plan across venues, then executes it.

You bring the forecast. Prophet decides where, how and at what price to trade. It is a calculator, never an adviser: it doesn't forecast, and it doesn't tell you what to buy.

Stage What happens
Find Live public order books from every venue, normalised to one YES-view book. Markets are found through a market graph, never by guessing ids.
Match The same event is identified on each venue. Each contract's resolution rule is graded against the canonical rule (A = identical, B = basis risk).
Compare Price, depth, each venue's exact fee schedule, fill probability, liquidity rewards and adverse selection.
Route The cheapest consolidated order across venues, never worse than the best single venue. Take now, or rest an order with a fallback.

Status. The live sample covers the 2028 US presidential election: 50 markets ("who wins", by candidate and by party) on Kalshi, Polymarket US and Polymarket (international). Execution is paper only. Fills are simulated against live order books, and no real orders are sent.

How it works

  1. Find a market. Call search_markets with a name, or browse_markets with a path such as Politics > California. Both return an event_id.
  2. Quote. Send an intent to get_quote. It has no side effects and returns a plan_id that stays firm for 30 seconds in paper mode.
  3. Execute. Call execute_plan with that plan_id and an idempotency_key. Prophet re-checks the plan against fresh books, then fills it.
  4. Track. Call get_execution to see the status, fills and slippage against the plan.

There are higher-level tools too. plan_view turns one view ("Newsom wins") into every market it implies. analyze_entry_exit shows where to enter or exit a book, and plan_exit decides whether to hold or sell.

Ground rules

These apply to every surface: REST, MCP, the console and the built-in agents.

  1. Find markets through the graph. Use search_markets or browse_markets to get an event_id. Don't guess ids.
  2. Quote before you execute. get_quote only stores the plan. execute_plan commits.
  3. Use a fresh idempotency_key for each new execution. If a call times out or you are unsure whether it went through, retry with the same key. You get the original execution back, not a second trade.
  4. Paper is the default. mode="paper" simulates fills against live order books. Live trading is disabled in this build.
  5. Books are always live. Every priced call fetches its order books from the venues during that call. Nothing cached is priced from. A venue that doesn't answer in time is excluded (VENUE_UNAVAILABLE), never served stale.
  6. Plans expire after 30 s in paper mode. On PLAN_EXPIRED, quote again. On PLAN_DRIFTED, review details.refreshed_plan and execute that one if it is still acceptable.
  7. Read risks. Contracts that look the same can resolve differently (see equivalence grades).
  8. Money is decimal strings. Prices are in dollars per $1 payout (for example "0.19"). Quantities are contracts. Field names carry units: price_usd, qty_contracts, notional_usd. No floating-point rounding ever touches a price or a fee.

Venues and grades

Each event has a canonical rule: "Resolves YES if X wins the 2028 US presidential election, as decided by the Electoral College." Each venue's contract is graded against it.

Venue Resolves on Grade Tradable by a US operator
Polymarket US Electoral College winner A (canonical) Yes
Kalshi Person or party inaugurated in January 2029 B Yes
Polymarket (intl) Winner as called by AP, Fox and NBC (inauguration fallback) B No (view only)

Grade-B contracts can diverge from the canonical event, for example in a contested result, or if the winner dies or is disqualified before inauguration. By default only grade-A venues are used. To let Prophet use Kalshi as well, which is often cheaper or deeper, opt in:

json
"equivalence": {"min_grade": "B", "allow_basis_risk": true}

The plan then lists each grade-B leg under risks with the code BASIS_RISK.

Fees come from each venue's published schedule, applied with that venue's exact rounding:

Venue Fee model
Kalshi Taker 0.07 × multiplier × C × P × (1 − P). Maker 0.0175 × multiplier on series with maker fees. Rounded per order.
Polymarket US Taker 0.0695 × C × p × (1 − p). Maker rebates by tier. Banker's rounding to the cent per fill.
Polymarket (intl) Taker C × rate × p × (1 − p) from the market's fee schedule (0 on fee-free markets). Makers pay nothing.

If a venue publishes a fee structure Prophet doesn't recognise, that venue is excluded. A fee is never guessed.

Quickstart

Quickstart

Get from zero to a filled paper trade in five commands. This assumes a running server (see Run it yourself to start one) and an API key.

1. Set your key and the API address.

shell
export PROPHET_API_URL=http://127.0.0.1:8000
export PROPHET_API_KEY=pk_...        # from `make key`, shown once

2. Check that it's up. You should see "ok": true and each venue's status.

shell
curl -s $PROPHET_API_URL/healthz

3. Find a market.

shell
curl -s "$PROPHET_API_URL/v1/markets?q=vance&limit=3" \
  -H "Authorization: Bearer $PROPHET_API_KEY"

4. Get a quote. This asks what it would cost to buy $100 of JD Vance YES, but only with edge against a 30% view. A quote never trades.

curl -s -X POST "$PROPHET_API_URL/v1/quotes" \
  -H "Authorization: Bearer $PROPHET_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "market": {"event_id": "evt_pres28_jd_vance"},
    "action": "buy", "outcome": "YES",
    "size": {"notional_usd": "100"},
    "view": {"p_yes": "0.30", "confidence": "medium"},
    "min_edge_bps": "300",
    "equivalence": {"min_grade": "B", "allow_basis_risk": true},
    "mode": "paper"
  }'

The response has a summary such as "Buy 498 YES at ~$0.2007 all-in ($99.95); 498 on Polymarket US.", plus a plan_id.

5. Execute it within 30 seconds.

shell
curl -s -X POST "$PROPHET_API_URL/v1/executions" \
  -H "Authorization: Bearer $PROPHET_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"plan_id\": \"<PLAN_ID>\", \"idempotency_key\": \"$(uuidgen)\", \"mode\": \"paper\"}"

You get back an execution with "status": "filled", the fills, the average all-in price and the slippage against the plan. See it in your positions with GET/v1/portfolio.

Prefer plain English? Skip the JSON and ask in plain English instead.

Run it yourself

Install

Prophet is one Python backend (REST, MCP and market data) plus one Next.js web app (the intro site and the console). It runs on macOS or Linux with Python 3.12, Postgres 16 and Node. Run every command from the repo root.

macOS prerequisites:

shell
brew install uv colima docker docker-compose node
uv python install 3.12
colima start                      # a Docker runtime for Postgres

One-time setup:

shell
cp .env.example .env              # safe defaults; never commit .env
make install                      # backend dependencies (uv sync)
make db-up                        # Postgres 16 in Docker, bound to 127.0.0.1:5432
make migrate                      # create the tables
make doctor                       # checks Python, the safety gates and the database

Create an API key

shell
make key NAME=me SCOPES=read,quote,execute_paper,admin

The key (pk_...) is printed once. Only its hash is stored, so save it somewhere safe. Leave out admin for keys you give to agents. See scopes for what each scope allows.

Start the servers

What Command Address
Backend: REST /v1, MCP /mcp/, live market data, resting-order simulator make api http://127.0.0.1:8000
Intro site /, console /app, these docs /docs.html make web-dev http://127.0.0.1:3000
MCP over stdio, for desktop clients PROPHET_API_KEY=pk_... make mcp-stdio stdin / stdout

On startup the backend rediscovers every market, rule, tick size and fee from the venues. That takes about 20 seconds and repeats hourly. Check it with curl -s localhost:8000/healthz. Interactive API docs are at http://127.0.0.1:8000/docs while it runs.

To use the web console, set it up once:

shell
cp web/.env.example web/.env.local   # put your key in PROPHET_API_KEY
make web-install
make web-dev

Open http://127.0.0.1:3000/app and either paste your key, or click Continue as local operator (enabled by PROPHET_WEB_LOCAL_LOGIN=true in web/.env.local).

Never enable PROPHET_WEB_LOCAL_LOGIN on a deployment other people can reach. Anyone who can open /login could then use your key.

To turn on the built-in Claude agents, add ANTHROPIC_API_KEY=sk-ant-... to .env and restart make api. Without it, GET/v1/agents reports available: false. Every agent turn spends real tokens.

Stop the servers

Press Ctrl-C in each terminal, or free the ports:

shell
kill $(lsof -ti tcp:8000) $(lsof -ti tcp:3000)
make db-down                         # stops Postgres; the data volume is kept

To run a second copy next to one that's already running, change the port: PROPHET_API_PORT=8001 uv --directory backend run prophet serve.

Configuration

Settings are environment variables, read from .env at the repo root. Backend settings start with PROPHET_. The defaults in .env.example are safe for local use.

Variable Default What it does
PROPHET_DATABASE_URL local compose Postgres Postgres connection string
PROPHET_API_HOST / PROPHET_API_PORT 127.0.0.1 / 8000 Where the backend listens
PROPHET_DEFAULT_MODE paper live is refused unless live trading is enabled
PROPHET_LIVE_TRADING_ENABLED false Safety gate. Live order placement isn't built yet.
PROPHET_THIRD_PARTY_EXECUTION false Startup fails if true (pending legal sign-off)
PROPHET_KILL_SWITCH_GLOBAL false Start with all execution halted
PROPHET_JURISDICTION US Decides which venues are tradable
PROPHET_PLAN_TTL_PAPER_S 30 How long a paper plan stays firm
PROPHET_PAPER_STARTING_CASH_USD 10000 Paper cash per venue
PROPHET_MAX_NOTIONAL_PER_ORDER_USD 1000 Risk limit per execution
PROPHET_MAX_NOTIONAL_PER_DAY_USD 5000 Risk limit per key per day
PROPHET_MAX_NOTIONAL_PER_EVENT_USD 2000 Risk limit per event
PROPHET_MAX_OPEN_EXECUTIONS 20 Working executions allowed at once
PROPHET_REFRESH_TIMEOUT_S 2 How long a request waits for live books
PROPHET_POLL_INTERVAL_S 3 Background book polling
PROPHET_CATALOG_LIVE / PROPHET_CATALOG_REFRESH_S true / 3600 Rediscover markets at startup and on this interval
PROPHET_RECORD_DIR unset If set, raw venue payloads are appended as JSONL
PROPHET_LOG_LEVEL / PROPHET_LOG_JSON INFO / true Logging (secrets are always redacted)
ANTHROPIC_API_KEY unset Turns on the built-in agents
PROPHET_AGENT_MODEL / PROPHET_AGENT_EFFORT claude-opus-5-5 / medium Model and effort for the built-in agents
PROPHET_API_KEY unset The key make mcp-stdio uses

The web app reads web/.env.local: PROPHET_API_URL (the backend, default http://127.0.0.1:8000), PROPHET_API_KEY (used only by local login) and PROPHET_WEB_LOCAL_LOGIN. These stay on the server and never reach the browser.

Deploy

The hosted setup is the web app on Vercel and the backend on Fly.io, with a Postgres database on either Fly Managed Postgres or Supabase. The repo has a backend/Dockerfile and a fly.toml. Migrations run automatically on every deploy.

Run exactly one backend machine for now. Order books, rate limits, the kill switch and resting paper orders live in memory. Every key also shares one paper portfolio until accounts land, so give keys only to people you trust.

1. Install the Fly CLI and log in (opens a browser):

shell
brew install flyctl
fly auth login

2. Create the app and its database. Pick a unique app name, then put the same name in fly.toml (app = "...").

shell
fly launch --no-deploy --copy-config --name <your-app-name>   # decline any database it offers

Then create the database in one of two ways.

# Create a project in the US East region (close to Fly's iad), then copy
# Connect → Session pooler → URI. Avoid the transaction pooler (port 6543).
read -rs DATABASE_URL                  # paste the URI with your password filled in
fly secrets set --app <your-app-name> DATABASE_URL="${DATABASE_URL}?sslmode=require"

The backend reads DATABASE_URL when PROPHET_DATABASE_URL isn't set, and converts the postgres:// form for its driver. With Supabase, use the session pooler. It works over IPv4 and supports the prepared statements the driver uses, which the transaction pooler doesn't. If your password contains @, :, / or #, URL-encode it (@ is %40). A migration revokes Supabase's anon and authenticated roles from every table and turns on row level security, so the Data API can't read your keys or trades.

3. Deploy.

shell
fly deploy --ha=false
curl -s https://<your-app-name>.fly.dev/healthz

4. Bring your API key. Either import a key you already have, so the same key works locally and in production:

shell
read -rs PROPHET_IMPORT_KEY            # paste the key; it isn't echoed or saved in shell history
echo "$PROPHET_IMPORT_KEY" | fly ssh console --app <your-app-name> --pty=false \
  -C "/app/backend/.venv/bin/prophet keys import --name test --scopes read,quote,execute_paper,admin"

Or create a new one on the server: fly ssh console --app <your-app-name> -C "/app/backend/.venv/bin/prophet keys create --name me --scopes read,quote,execute_paper,admin".

The import reads the key from stdin or PROPHET_IMPORT_KEY, never from the command line, and stores only its hash. Importing the same key twice is harmless.

5. Point the web app at it. In Vercel, open the project (Root Directory web) and go to Settings → Environment Variables. Set PROPHET_API_URL to https://<your-app-name>.fly.dev, then redeploy. Don't set PROPHET_WEB_LOCAL_LOGIN there. Log in at https://<your-vercel-domain>/login with your key.

Optional: to turn on the built-in agents, run fly secrets set ANTHROPIC_API_KEY=sk-ant-....

Updating

shell
git pull
make install && make migrate         # new dependencies and migrations
make web-install                     # if web/package.json changed

Then restart make api and make web-dev. Contributors should also read the runbook for tests, migrations and debugging.

Ask in plain English

Plain English

You don't need to write JSON. There are four ways to type a question or an instruction, such as "I think Newsom is 20% to win. Buy $50 of YES if there's edge.", and have it carried out. All four use the same tools and the same rules, and none of them executes without your approval.

Option Best for Needs
The console desk Clicking around, watching plans and fills make web-dev, ANTHROPIC_API_KEY on the backend
The example script A terminal chat, or a starting point for your own agent ANTHROPIC_API_KEY where you run it
Claude Code, Claude Desktop or Cursor Using an assistant you already have That app
The agents API Building a chat UI on top of the built-in agents ANTHROPIC_API_KEY on the backend

Console desk

Open /app and pick an agent:

Agent What it does
Forecaster Researches the race (it can search the web), forms its own probability, then finds the best entry
Trader Turns your instructions into the cheapest, best-placed orders across venues
Exit manager Reviews your positions and finds where to exit, or whether to hold

Type what you want. The agent quotes and analyses freely. Before it executes or cancels anything, it stops and shows you an approval card. Nothing happens until you click approve. The other console pages are:

  • Markets: every event, with per-venue prices and depth.
  • Quote & execute: build an intent by hand.
  • Agent console: the audit trail of what every agent did.
  • Portfolio: positions, balances and price improvement.

The intro site's chatbox hands off to the console as /app?agent=trader&q=.... That only fills in the composer. It never sends anything by itself.

Example script

examples/external_agent.py is an outside agent in about 180 lines. It connects over MCP like any third-party agent would, gives Claude the tools, and asks you y/N in the terminal before every execution. Paper mode only.

shell
make api                                                           # terminal 1
uv --directory backend run python ../examples/external_agent.py    # terminal 2
connected to http://127.0.0.1:8000/mcp/ (16 tools). Type a command, or 'quit'.

you> what's Newsom trading at on each venue?
you> I think he's 20% to win. Buy $50 of YES if there's edge
  execute plan pln_... in paper mode? [y/N] y
you> show my portfolio
Flag Effect
"some text" Run one command and exit
-v Show every tool call and its raw result
--model claude-opus-5-5 Use a different model (default claude-sonnet-5-5)
--demo A fixed search → quote → execute → portfolio run, with no LLM

It reads PROPHET_API_KEY from your environment or web/.env.local, and ANTHROPIC_API_KEY from your environment or .env. Set PROPHET_MCP_URL to point it at another server.

MCP clients

Add Prophet as an MCP server and just talk to the assistant. See Connect your agent for the exact configuration for Claude Code, Claude Desktop and Cursor.

shell
claude mcp add --transport http prophet http://127.0.0.1:8000/mcp/ \
  --header "Authorization: Bearer <KEY>"

Then, in Claude Code: "Using prophet, compare Vance YES across venues for 500 contracts."

Your own agent's client decides whether to ask before executing. Prophet marks execute_plan as destructive and idempotent in its MCP annotations so clients can prompt you.

Good things to ask

  • "Search for every Democrat and show me their best ask."
  • "What would $200 of Newsom YES cost on each venue, all-in?"
  • "Browse Politics > California and list the markets."
  • "I think Vance is 25%. Quote $100 of YES with at least 3% edge, Kalshi allowed."
  • "My view: Newsom wins at 15%, medium confidence. Plan it with $500 and risk tolerance 0.25."
  • "Should I enter Vance YES now or post a bid? I think he's 22%."
  • "Review my positions. Should I hold or exit, given Vance at 18%?"
  • "Explain the last plan, and why Polymarket intl was excluded."

Agents never choose your capital, risk tolerance or probability. If you leave one out, a well-behaved agent asks.

Connect your agent

Authentication

Every request carries a bearer API key:

Authorization: Bearer pk_...

Only a hash of the key is stored. Every call is written to an append-only audit log, with the key, the surface (REST or MCP) and the arguments.

Scope Allows
read Markets, the graph, plans and their explanations, executions, entry/exit analysis, exit plans, sizing, portfolio, limits, venue health
quote get_quote and plan_view, which create plans
execute_paper Executing and cancelling in paper mode, and approving built-in agent actions
execute_live Live execution. Reserved: live trading is disabled in this build.
admin The audit log, API keys and the kill switch

make key without SCOPES creates a key with read,quote,execute_paper. The web console uses the same keys. It keeps yours in an httpOnly cookie on the server, where page scripts can't read it.

MCP

Prophet is an MCP server. Agents get 16 tools (see the tool reference) plus three resources:

  • prophet://venues: venue health and eligibility.
  • prophet://event/{event_id}/rules: the canonical rule and each venue's resolution rule.
  • prophet://docs/agent-guide: the agent sections of this guide.

Streamable HTTP (stateless) at http://127.0.0.1:8000/mcp/, with the Authorization header. Mind the trailing slash.

Claude Code
claude mcp add --transport http prophet http://127.0.0.1:8000/mcp/ \
  --header "Authorization: Bearer <KEY>"
Cursor (.cursor/mcp.json)
{
  "mcpServers": {
    "prophet": {
      "url": "http://127.0.0.1:8000/mcp/",
      "headers": {"Authorization": "Bearer <KEY>"}
    }
  }
}

stdio, for clients that launch the server themselves. The key comes from PROPHET_API_KEY:

Claude Desktop (claude_desktop_config.json)
{
  "mcpServers": {
    "prophet": {
      "command": "uv",
      "args": ["--directory", "<repo>/backend", "run", "prophet", "mcp-stdio"],
      "env": {"PROPHET_API_KEY": "<KEY>"}
    }
  }
}

From your own code, with the Python MCP SDK. This is the core of examples/external_agent.py:

python
import asyncio, httpx2
from mcp import Client
from mcp.client.streamable_http import streamable_http_client

async def main():
    http = httpx2.AsyncClient(headers={"Authorization": "Bearer <KEY>"}, timeout=60)
    async with Client(streamable_http_client("http://127.0.0.1:8000/mcp/", http_client=http)) as c:
        r = await c.call_tool("search_markets", {"query": "Vance", "limit": 3})
        print(r.structured_content)

asyncio.run(main())

Errors arrive as tool errors whose text is the JSON error envelope.

REST

The same operations are available under /v1. Each MCP tool maps to one route (see the tool reference). The OpenAPI schema is at GET/openapi.json (also committed as docs/openapi.json), and interactive docs are at /docs on the backend.

  • Requests and responses are JSON. Every money value is a decimal string in both directions.
  • Errors use HTTP status codes plus the error envelope.
  • To label your agent in the audit log, send an X-Agent header, for example X-Agent: my-bot/1.2.
  • Two routes stream server-sent events: execution events and agent messages.
Find markets

Search and browse

Search by name with search_markets. REST is GET/v1/markets, with q, optional repeated venues, and limit.

shell
curl -s "$PROPHET_API_URL/v1/markets?q=Democratic%20party" -H "Authorization: Bearer $PROPHET_API_KEY"

Each result has an event_id and, per venue: bid, ask, depth, grade, eligibility and how fresh the book is.

Browse the graph with browse_markets. REST is GET/v1/graph/browse?path=.... A path is >-separated, and each segment narrows the result. A segment can be a topic, person, party, state or outcome set.

Path Returns
Politics > California Every Californian's market
Democrats > Michigan Democrats from Michigan
Politics > California > Presidential Election > Gavin Newsom Exactly Newsom's market

The response lists how each segment was resolved, any unresolved segments, and the matching markets with live prices.

The market graph

Markets hang in a graph, and every edge can be walked in both directions:

  • Topics: Politics › US Politics › US Elections › 2028 Presidential Election, plus US States and Parties.
  • Outcome sets: "2028 Presidential: winner" (exactly one person wins) and "2028 Presidential: party".
  • Entities: people (with their curated party and home state), parties and states.
  • Markets (canonical events) and their venue contracts.

There are also logical edges. A candidate's market implies their party's market, and the outcomes in an exclusive set exclude each other. Views use these edges to find every leg a view implies.

Inspect one node with get_graph_node. REST is GET/v1/graph/nodes/{ref}, where ref is an id or a name, for example Gavin Newsom. It returns the node, its topic paths, every edge, and every market under it. GET/v1/graph exports the whole graph.

Market detail and comparison

One market: get_market(event_id, detail), or GET/v1/markets/{event_id}. It returns per-venue prices, depth, fees, the canonical rule and each venue's rule differences. detail="full" adds order book ladders and the full rule text.

Compare venues at a size: compare_venues(event_id, action, outcome, size), or GET/v1/markets/{event_id}/compare?action=buy&outcome=YES&size=500. It returns the all-in cost (price plus fees) of that size on each venue, the best single venue, and the consolidated cost across venues. This is information only: it isn't an arbitrage signal.

shell
curl -s "$PROPHET_API_URL/v1/markets/evt_pres28_gavin_newsom/compare?action=buy&outcome=YES&size=500" \
  -H "Authorization: Bearer $PROPHET_API_KEY"
Quote and execute

Intents

An intent says what you want. Send it to get_quote, or POST/v1/quotes. Prophet then:

  1. resolves the event;
  2. fetches live books;
  3. filters venues by eligibility, grade and freshness;
  4. sizes the order;
  5. applies your edge requirement;
  6. routes across venues, deciding for each leg whether to take now or rest an order.
json
{
  "market": {"event_id": "evt_pres28_gavin_newsom"},
  "action": "buy",
  "outcome": "YES",
  "size": {"notional_usd": "100"},
  "limit_price": "0.25",
  "view": {"p_yes": "0.20", "confidence": "medium"},
  "min_edge_bps": "300",
  "urgency": "normal",
  "horizon_seconds": 300,
  "venues": {"allow": ["kalshi", "polymarket_us"]},
  "equivalence": {"min_grade": "B", "allow_basis_risk": true},
  "max_slippage_bps": "50",
  "mode": "paper"
}
Field Default Meaning
market required {"event_id": "..."}, or {"query": "newsom"}. A query that matches several events fails with AMBIGUOUS_MARKET and lists details.candidates.
action, outcome required, YES buy or sell, and YES or NO. Buying NO is the same as selling YES at 1 − price; Prophet handles the conversion. You can only sell what you hold.
size required {"contracts": "250"}, or {"notional_usd": "100"} (buys only). Notional sizing buys the largest whole number of contracts whose all-in cost fits the budget.
limit_price none The worst price you accept, per contract
view none Your probability p_yes, with confidence low, medium or high. Prophet shrinks it toward the market price by 60%, 30% or 10% respectively.
min_edge_bps 0 Use only liquidity whose all-in price, after fees, beats the adjusted view by at least this much. If none qualifies, you get EDGE_BELOW_THRESHOLD with details.break_even_price.
urgency immediate immediate takes liquidity now. normal may rest a join or improve order for horizon_seconds, then cross the remainder 30 s before the deadline, within the fallback limit. patient rests the order and cancels whatever is unfilled.
horizon_seconds 300 How long a resting order may work
venues.allow all Restrict to these venues
equivalence A, no basis risk Set min_grade: "B" and allow_basis_risk: true to use grade-B venues (grades)
max_slippage_bps 50 At execution, a plan that has moved more than this is refused with PLAN_DRIFTED
max_fee_bps none Refuse the plan (LIMIT_EXCEEDED, with details.fee_bps) if total fees exceed this share of notional
mode paper live is refused in this build

Prophet only rests an order when doing so beats taking by at least $0.0005 per contract, after fill risk, adverse selection and the cost of waiting.

Plans

The quote returns a plan:

json
{
  "plan_id": "pln_...",
  "expires_at": "2026-11-10T14:02:41Z",
  "summary": "Buy 725 YES at ~$0.1244 all-in ($90.17); 725 on Kalshi.",
  "legs": [{
    "venue": "kalshi", "action": "buy", "outcome": "YES",
    "tactic": "post_improve", "limit_price": "0.121", "qty": "725",
    "ttl_seconds": 300, "expected_fee_usd": "0", "grade": "B"
  }],
  "totals": {"expected_avg_all_in": "0.1244", "worst_case_avg_all_in": "0.1379"},
  "benchmark": {"best_single_venue": "kalshi", "improvement_bps": "0"},
  "edge": {"view_p": "0.2", "adjusted_view_p": "0.1805", "net_edge_bps": "620.83"},
  "risks": [{"code": "BASIS_RISK", "severity": "warn", "detail": "..."}],
  "excluded": {"polymarket": "VENUE_INELIGIBLE"}
}
  • legs: one per venue order, with its tactic (take_ioc, post_join or post_improve), price, size, expected fee and grade.
  • benchmark: the best single venue at the same size. The plan is never worse: improvement_bps ≥ 0.
  • risks: things to read before you execute, such as basis risk, low fill probability or a size reduced to keep your edge.
  • excluded: each venue that wasn't used, and why.

Get the plan again with GET/v1/plans/{plan_id}. Get its reasoning, risks and the alternatives considered with explain_plan, or GET/v1/plans/{plan_id}/explain.

Execute

execute_plan(plan_id, idempotency_key, mode), or POST/v1/executions:

json
{"plan_id": "pln_...", "idempotency_key": "6f1c2a90-vance-1", "mode": "paper"}

Executing re-checks everything first: that the plan hasn't expired, the risk limits, the kill switches, and your position if you're selling. It also re-quotes on fresh books. If the price has moved more than max_slippage_bps, you get PLAN_DRIFTED with details.refreshed_plan instead of a worse fill.

  • Idempotent. The same key always returns the same execution, and a plan executes at most once. Reusing a key for a different plan fails with IDEMPOTENCY_CONFLICT.
  • Take legs fill immediately. Resting legs stay working until they fill, expire or are cancelled.

Track and cancel

shell
# Long-poll up to 10 s for a final status
curl -s "$PROPHET_API_URL/v1/executions/<EXECUTION_ID>?wait_ms=5000" -H "Authorization: Bearer $PROPHET_API_KEY"

# Or stream every change as server-sent events: execution, then done (or error)
curl -N "$PROPHET_API_URL/v1/executions/<EXECUTION_ID>/events" -H "Authorization: Bearer $PROPHET_API_KEY"

An execution reports its status, each order with its fills and fees, the average all-in price, and slippage_vs_plan_bps. List recent executions with GET/v1/executions?limit=20. Cancel any working orders with cancel_execution, or POST/v1/executions/{id}/cancel. Take legs are immediate-or-cancel, so usually nothing is left to cancel.

Views

Views

plan_view, or POST/v1/views, takes one view and uses the graph to find every market leg that pays whenever the view is true. It then sizes those legs together against live books.

json
{
  "subject": "Gavin Newsom",
  "outcome": "YES",
  "p": "0.15",
  "confidence": "medium",
  "capital_usd": "500",
  "risk_tolerance": "0.25"
}

For "Newsom wins", the implied legs are:

  • YES on Newsom (direct);
  • NO on Rubio, NO on Vance, and so on (excludes: only one person can win);
  • YES on the Democratic Party and NO on the Republican Party (implies: Newsom is a Democrat).
Field Default Meaning
subject required A person, party, event_id or contract id
outcome, p, confidence YES, required, medium Your probability that the subject's market resolves outcome. It is shrunk toward the market by confidence, as in quotes.
capital_usd required The most this view may spend
risk_tolerance required In (0, 1]. 0.05 is cautious, 0.25 moderate and 1 aggressive. It mostly scales size.
max_loss_usd capital_usd Cap on the loss in the worst scenario
min_win_prob 0 Only buy legs at least this likely to pay under your view
min_edge_bps 100 Per-contract edge floor, in bps of $1
max_legs 8 1 to 20
venues, equivalence all, grade A As in intents
create_plans true Create an executable paper plan for each allocated leg

You set capital_usd and risk_tolerance. Agents must not choose them for you.

How it decides. Your p goes to the subject. The rest of the probability is spread over the other outcomes in proportion to their live prices. "An unlisted Democrat" and "someone unlisted" are separate scenarios, so "Democrats lose" never means "Republicans win". A leg is only counted as paying in a scenario when that payout is certain.

Allocation maximises expected exponential (CARA) utility with risk tolerance τ = risk_tolerance × capital_usd. It always stays within capital_usd, max_loss_usd, min_edge_bps and max_legs.

Which legs get chosen depends on price. If the rival markets are fairly priced, NO on a rival is just a diluted copy of the direct leg, so the direct leg wins. NO-on-rival legs win when they are priced better, or when the direct book runs out. To prefer likely legs, raise min_win_prob (for example to 0.7). That usually leaves NO on rivals.

Output. Each leg has its relation and reason, p_win, the live all-in cost, its edge and a status:

Status Meaning
planned Allocated, with a normal paper plan_id. Execute it with execute_plan.
not_allocated Had edge, but the optimiser gave it nothing
no_edge Below min_edge_bps
below_min_win_prob Less likely to pay than min_win_prob
no_liquidity No usable book

The portfolio summary shows the total cost, expected PnL, the minimum PnL if the view is right, the worst case and P(profit). A view touches about 50 markets, so it takes 3–6 seconds. Like everything else here, it is a calculator relative to your view, not advice.

Entry and exit

Entry and exit analysis

analyze_entry_exit, or POST/v1/analysis, shows where to enter or exit a book. For each venue it compares taking now against joining the best price or improving on it.

json
{
  "event_id": "evt_pres28_gavin_newsom",
  "action": "buy",
  "outcome": "YES",
  "size_contracts": "200",
  "p_yes": "0.20",
  "horizon_seconds": 300,
  "urgency": "normal"
}

Each option shows:

  • Fill probability: from recent taker flow and your place in the queue. Polymarket US flow is inferred from volume changes and flagged inferred.
  • Fees: maker versus taker, from each venue's verified schedule.
  • Rewards: liquidity-reward estimates from the Polymarket and Kalshi programs, haircut 50% and used only as a tie-break.
  • Adverse selection: the expected cost of being filled by better-informed traders.
  • Expected profit: at your p_yes.

Exit plans

plan_exit, or POST/v1/exits, looks at every position you hold on an event. For each one it weighs holding to resolution against selling now or resting an exit order.

json
{"event_id": "evt_pres28_jd_vance", "p_yes": "0.18", "horizon_seconds": 300}

When exiting is better, the response includes an executable sell plan. Set "build_plan": false to skip it. Execute it like any other plan.

Account and operations

Portfolio and limits

  • get_portfolio, or GET/v1/portfolio: your paper positions (venue, contract, event, outcome, quantity, average cost, mark, unrealised PnL) and the cash on each venue. Each venue starts with PROPHET_PAPER_STARTING_CASH_USD of paper cash.
  • get_limits, or GET/v1/limits: your key's scopes and risk limits (per order, per day, per event, open executions), today's usage, and whether the kill switch is engaged. An execution over a limit fails with LIMIT_EXCEEDED.

Position sizing

calc_position_size, or POST/v1/sizing, suggests a stake from your probability and bankroll. It's a calculator, not advice.

json
{"p_yes": "0.20", "bankroll_usd": "1000", "policy": "fractional_kelly", "event_id": "evt_pres28_gavin_newsom"}
Field Default Meaning
policy proper_brier fixed, proper_brier or fractional_kelly
event_id or yes_price_usd one is required The price to size against: the median live mid across the event's venues, or a YES price you give
kelly_k 0.25 The Kelly fraction, for fractional_kelly
max_fraction 0.10 Never stake more than this share of the bankroll

It returns the side, price, stake in dollars, contracts and the fraction of the bankroll.

Operations

These need the admin scope, except reading the kill switch, which needs read.

Task Route
Venue health, eligibility, freshness and the market catalog source GET/v1/venues (scope read)
The audit log: every call by every key and agent GET/v1/audit?limit=100&after_id=0
Read the kill switch GET/v1/admin/kill-switch
Halt all execution, or one venue with ?venue=kalshi POST/v1/admin/kill-switch, body {"engaged": true}
List API keys GET/v1/admin/keys
Create a key (shown once) POST/v1/admin/keys?name=bot&scopes=read&scopes=quote
Revoke a key POST/v1/admin/keys/{key_id}/revoke

The logs are JSON on stdout, with keys, signatures and tokens redacted. Correlate entries by plan_id and execution_id.

Built-in agents API

Agents API

The console's agents are available over REST, so you can build your own chat UI on them. They need ANTHROPIC_API_KEY on the backend. Without it, GET/v1/agents reports available: false and messages fail with AGENT_UNAVAILABLE.

Step Route
List agents: id, name, tagline, tools, starter prompts, model, availability GET/v1/agents
Start a conversation (forecaster, trader or exit_manager) POST/v1/agents/{agent_id}/conversations, body {"title": ""}
Send a message (streams the reply) POST/v1/conversations/{id}/messages, body {"text": "..."}
Approve or decline a paused action (streams the rest of the reply) POST/v1/conversations/{id}/approvals/{tool_use_id}, body {"approve": true}
List your conversations, or reload one with its messages GET/v1/conversations?agent_id=trader, GET/v1/conversations/{id}

Messages and approvals reply with server-sent events. Each has an event: name and a JSON data: line.

Event Data
text / thinking A chunk of the reply, or of the agent's reasoning
tool_call / tool_result A tool the agent called, and what it returned
focus The event the conversation is now about
approval_required The agent wants to run execute_plan or cancel_execution. pending lists each call with its tool_use_id, its input and, for executions, a preview of the plan. The stream then ends.
usage Token usage for the turn
error An error envelope
done The turn is over
shell
CONV=$(curl -s -X POST $PROPHET_API_URL/v1/agents/trader/conversations \
  -H "Authorization: Bearer $PROPHET_API_KEY" -H "Content-Type: application/json" -d '{}' | jq -r .conversation_id)

curl -N -X POST $PROPHET_API_URL/v1/conversations/$CONV/messages \
  -H "Authorization: Bearer $PROPHET_API_KEY" -H "Content-Type: application/json" \
  -d '{"text": "Quote $50 of Newsom YES with Kalshi allowed"}'

Agents can execute only through this approval step, only in paper mode, and approving needs the execute_paper scope. There is no auto-approval.

Reference

Tools

Every MCP tool and the REST route that does the same thing. Tests check this table against the running server's tool list.

Tool REST Scope What it does
search_markets GET/v1/markets read Find events by name, with per-venue bid, ask, depth, grade and freshness
browse_markets GET/v1/graph/browse read Walk the market graph by a >-separated path
get_graph_node GET/v1/graph/nodes/{ref} read One graph node: topic paths, every edge, the markets under it
get_market GET/v1/markets/{event_id} read One event's per-venue prices, depth, fees and rule differences. detail="full" adds ladders.
compare_venues GET/v1/markets/{event_id}/compare read The all-in cost of a size on each venue, side by side
get_quote POST/v1/quotes quote Turn an intent into a plan, firm for 30 s
explain_plan GET/v1/plans/{plan_id}/explain read A plan's reasoning, risks and alternatives
execute_plan POST/v1/executions execute_paper Commit a plan. Destructive and idempotent.
get_execution GET/v1/executions/{execution_id} read Status, fills and slippage. wait_ms long-polls up to 10 s.
cancel_execution POST/v1/executions/{execution_id}/cancel execute_paper Cancel working orders
plan_view POST/v1/views quote Turn a view into every implied market leg, sized by CARA
analyze_entry_exit POST/v1/analysis read Take now versus join or improve, on each venue
plan_exit POST/v1/exits read Hold, sell now or rest an exit order, for each of your positions
get_portfolio GET/v1/portfolio read Paper positions and cash
get_limits GET/v1/limits read Risk limits and today's usage
calc_position_size POST/v1/sizing read Suggest a stake from a probability and bankroll

Endpoints

Every REST route. Tests check this table against the OpenAPI schema.

Route Purpose
GET/healthz Liveness, the event count and each venue's status (no key needed)
GET/v1/markets Search markets
GET/v1/markets/{event_id} Market detail
GET/v1/markets/{event_id}/compare Compare venues at a size
GET/v1/graph Export the whole market graph
GET/v1/graph/browse Browse by path
GET/v1/graph/nodes/{ref} One graph node
POST/v1/quotes Get a quote (a plan)
GET/v1/plans/{plan_id} Read a plan
GET/v1/plans/{plan_id}/explain Explain a plan
POST/v1/views Plan a view
POST/v1/executions Execute a plan
GET/v1/executions List executions
GET/v1/executions/{execution_id} Read an execution, optionally long-polling
GET/v1/executions/{execution_id}/events Stream an execution (SSE)
POST/v1/executions/{execution_id}/cancel Cancel an execution
POST/v1/analysis Entry and exit analysis
POST/v1/exits Exit plan
GET/v1/portfolio Portfolio
GET/v1/limits Limits
POST/v1/sizing Position sizing
GET/v1/venues Venue health and the catalog source
GET/v1/audit Audit log (admin)
GET/v1/admin/kill-switch Read the kill switch
POST/v1/admin/kill-switch Engage or release the kill switch (admin)
GET/v1/admin/keys List API keys (admin)
POST/v1/admin/keys Create an API key (admin)
POST/v1/admin/keys/{key_id}/revoke Revoke an API key (admin)
GET/v1/agents List built-in agents
POST/v1/agents/{agent_id}/conversations Start a conversation
GET/v1/conversations List conversations
GET/v1/conversations/{conversation_id} Read a conversation
POST/v1/conversations/{conversation_id}/messages Send a message (SSE)
POST/v1/conversations/{conversation_id}/approvals/{tool_use_id} Approve or decline an action (SSE)

Errors

Every error has the same envelope:

json
{"error": {"code": "PLAN_EXPIRED", "message": "...", "retryable": true,
           "suggested_action": "Call get_quote again and execute the new plan_id.", "details": {}}}

Over MCP, the tool error's text is the inner object. A request that fails schema validation gets FastAPI's standard 422 response instead, with detail listing each bad field.

Code What to do
UNAUTHORIZED 401. The bearer key is missing or invalid.
FORBIDDEN 403. The key lacks the scope this call needs.
NOT_FOUND Check the id. Use search_markets to find events.
INVALID_REQUEST Fix the request; message says what's wrong.
AMBIGUOUS_MARKET Pick one event_id from details.candidates.
STALE_BOOK Retryable. Retry in a few seconds.
VENUE_UNAVAILABLE Retryable. The venue didn't answer in time. Retry, or allow more venues.
MARKET_CLOSED Choose an open market.
VENUE_INELIGIBLE No venue is tradable from your jurisdiction. Use an eligible venue, such as Polymarket US for US operators.
RULES_MISMATCH Only grade-B venues are left. Opt in to basis risk with equivalence, or don't trade.
NO_LIQUIDITY_WITHIN_LIMIT Reduce size or relax limit_price.
EDGE_BELOW_THRESHOLD No liquidity has enough edge. See details.break_even_price; lower min_edge_bps, or skip.
LIMIT_EXCEEDED A risk limit or kill switch blocked it. details.violations lists which, for example MAX_NOTIONAL_PER_DAY or KILL_SWITCH. See get_limits.
PLAN_EXPIRED Retryable. Call get_quote again.
PLAN_DRIFTED Retryable. Review details.refreshed_plan, and execute it if it's still acceptable.
PLAN_ALREADY_EXECUTED 409. The plan was executed under another key; see details.execution_id. Quote again for a new trade.
IDEMPOTENCY_CONFLICT That key was used for a different plan. Use a new key.
INSUFFICIENT_POSITION You can only sell what you hold. See get_portfolio.
LIVE_DISABLED Use mode="paper". Live trading is off.
AGENT_UNAVAILABLE The built-in agents need ANTHROPIC_API_KEY on the backend.

Risk and exclusion codes

These appear in a plan's risks and excluded, and in execution status_reason. They are not errors.

Code Meaning
BASIS_RISK A grade-B leg is used, so it may resolve differently from the canonical rule
BASIS_RISK_NOT_ALLOWED A grade-B venue was skipped because you didn't opt in
VENUE_INELIGIBLE That venue isn't tradable from your jurisdiction (view only)
VENUE_NOT_ALLOWED Left out by your venues.allow
STALE_BOOK, VENUE_UNAVAILABLE, MARKET_CLOSED, CROSSED_BOOK No usable live book on that venue
UNSUPPORTED_FEES The venue's fee schedule isn't recognised, so it isn't guessed
SIZE_REDUCED_BY_EDGE Only part of the size meets your edge rule
LOW_FILL_PROBABILITY, PASSIVE_FILL_UNCERTAIN A resting order may not fill in time
MAX_RESTING_ORDERS, SELF_TRADE, RESTING_ORDERS_UNAVAILABLE A resting order was rejected
Help

Troubleshooting

Symptom Fix
curl: (7) Failed to connect to :8000 The backend isn't running. Start it with make api.
UNAUTHORIZED Send Authorization: Bearer pk_.... Keys are shown once; make a new one with make key.
FORBIDDEN The key lacks a scope. Check GET/v1/limits → scopes.
Backend won't start: database errors Run make db-up, then make migrate. On macOS, colima start first. make doctor checks all of this.
VENUE_UNAVAILABLE, or NO_LIVE_BOOK in excluded The venue didn't answer within the refresh timeout. Retry, or check GET/v1/venues.
RULES_MISMATCH or VENUE_INELIGIBLE on a quote Polymarket US is the only grade-A venue. Add "equivalence": {"min_grade": "B", "allow_basis_risk": true} to allow Kalshi.
PLAN_EXPIRED Paper plans last 30 s. Quote and execute in one go.
GET/v1/venues says catalog.source: "file" Live market discovery hasn't finished (about 20 s after startup) or failed. Check the logs.
Console redirects to /login Your session cookie is missing. Paste a key, or enable local login in web/.env.local.
Agents say unavailable Set ANTHROPIC_API_KEY in .env and restart make api.
A view is slow plan_view fetches about 50 live books; 3–6 s is normal.
Port already in use Something is already on :8000 or :3000. Stop it with kill $(lsof -ti tcp:8000), or set PROPHET_API_PORT.

FAQ

Does it place real orders? No. This build is paper only. Fills are simulated against live order books. Live trading needs the operator's explicit approval and is not built.

Where do prices come from? Each venue's public market-data API, fetched live during every priced call. Nothing older than the request is priced from.

Can I trade international Polymarket? Not from the US. It is shown for comparison and marked view-only. Prophet never evades geoblocks.

Does Prophet give advice? No. It is a calculator relative to the view you give it. It never picks your probability, capital or risk tolerance.

What does it cost? Prophet charges no fee here. Plans include each venue's own fees, applied with that venue's exact rounding.

How do I reset my paper portfolio? Paper fills are stored in Postgres. Wiping the database resets everything, including your API keys: docker compose down -v, then make db-up && make migrate.

Where can I ask a question or report a bug? Open an issue on the GitHub repository, or use the contact page.

For contributors

The docs for people changing Prophet itself live in the repo's docs/ folder: architecture.md (how it fits together), runbook.md (tests, migrations, debugging), update.md (the current state and the handoff log) and skills.md. Working, architecture and safety rules are in CLAUDE.md, and verified venue facts are in DECISIONS.md.

This guide is the single source for user docs. Edit the Markdown in docs/guide/, then run make docs. That rebuilds the site's docs page, docs/agent-guide.md (served to agents over MCP), llms.txt and llms-full.txt. make check fails if any of them is out of date, or if the guide disagrees with the code on tools, routes, errors, settings or request schemas.

Generated from docs/guide/. Found something wrong? Fix the Markdown and run make docs.