# List execution analytics (predicted vs realized) Source: https://docs.trymithril.com/api-reference/analytics/list-execution-analytics-predicted-vs-realized /api-reference/openapi.json get /v1/analytics/execution # Create API key Source: https://docs.trymithril.com/api-reference/api-keys/create-api-key /api-reference/openapi.json post /v1/api_keys # Revoke API key Source: https://docs.trymithril.com/api-reference/api-keys/revoke-api-key /api-reference/openapi.json delete /v1/api_keys/{id} # Cancel complex order Source: https://docs.trymithril.com/api-reference/complex-orders/cancel-complex-order /api-reference/openapi.json post /v1/complex_orders/{id}/cancel # Create complex order Source: https://docs.trymithril.com/api-reference/complex-orders/create-complex-order /api-reference/openapi.json post /v1/complex_orders # Get complex order Source: https://docs.trymithril.com/api-reference/complex-orders/get-complex-order /api-reference/openapi.json get /v1/complex_orders/{id} # Get complex order execution quality (TCA) Source: https://docs.trymithril.com/api-reference/complex-orders/get-complex-order-execution-quality-tca /api-reference/openapi.json get /v1/complex_orders/{id}/execution_report # List a complex order's child orders + queue positions Source: https://docs.trymithril.com/api-reference/complex-orders/list-a-complex-orders-child-orders-+-queue-positions /api-reference/openapi.json get /v1/complex_orders/{id}/children # List complex orders Source: https://docs.trymithril.com/api-reference/complex-orders/list-complex-orders /api-reference/openapi.json get /v1/complex_orders # Preview order impact + recommended plan Source: https://docs.trymithril.com/api-reference/complex-orders/preview-order-impact-+-recommended-plan /api-reference/openapi.json post /v1/complex_orders/preview # List fills Source: https://docs.trymithril.com/api-reference/fills/list-fills /api-reference/openapi.json get /v1/fills # Get market Source: https://docs.trymithril.com/api-reference/markets/get-market /api-reference/openapi.json get /v1/markets/{id} # Get market orderbook Source: https://docs.trymithril.com/api-reference/markets/get-market-orderbook /api-reference/openapi.json get /v1/markets/{id}/orderbook # Get market prices Source: https://docs.trymithril.com/api-reference/markets/get-market-prices /api-reference/openapi.json get /v1/markets/{id}/prices # Match markets Source: https://docs.trymithril.com/api-reference/markets/match-markets /api-reference/openapi.json post /v1/markets/match # Search markets Source: https://docs.trymithril.com/api-reference/markets/search-markets /api-reference/openapi.json get /v1/markets # Cancel all orders Source: https://docs.trymithril.com/api-reference/orders/cancel-all-orders /api-reference/openapi.json post /v1/orders/cancel_all # Cancel order Source: https://docs.trymithril.com/api-reference/orders/cancel-order /api-reference/openapi.json post /v1/orders/{id}/cancel # Get order Source: https://docs.trymithril.com/api-reference/orders/get-order /api-reference/openapi.json get /v1/orders/{id} # List orders Source: https://docs.trymithril.com/api-reference/orders/list-orders /api-reference/openapi.json get /v1/orders # Place order Source: https://docs.trymithril.com/api-reference/orders/place-order /api-reference/openapi.json post /v1/orders # API reference Source: https://docs.trymithril.com/api-reference/overview Every endpoint the gateway serves, with a live, machine-generated spec. Every endpoint is documented in the **Endpoints** section of this tab — an interactive reference with request/response schemas and a "try it" console, generated directly from the gateway's route table so it can't drift. Request and response **contracts** (field-by-field JSON with worked examples) also live in the [guides](/guides/orders). Open **Endpoints** in the sidebar to browse every operation with schemas and a live request console. Prefer the [Python SDK](/sdks/python) for real integrations — it wraps these endpoints with typed models and idempotency. ## Endpoint map All endpoints are under `https://api.trymithril.com/v1` and require a [bearer key](/authentication). ### Accounts | Method | Path | | -------- | --------------------------------------------- | | `GET` | `/v1/subaccounts` | | `POST` | `/v1/subaccounts` | | `GET` | `/v1/subaccounts/{id}` | | `DELETE` | `/v1/subaccounts/{id}` | | `PUT` | `/v1/subaccounts/{id}/credentials` | | `DELETE` | `/v1/subaccounts/{id}/credentials/{exchange}` | | `GET` | `/v1/subaccounts/{id}/balances` | ### Market data | Method | Path | | ------ | ---------------------------- | | `GET` | `/v1/markets` | | `GET` | `/v1/markets/{id}` | | `GET` | `/v1/markets/{id}/orderbook` | | `GET` | `/v1/markets/{id}/prices` | | `POST` | `/v1/markets/match` | ### Orders | Method | Path | | ------ | ------------------------ | | `POST` | `/v1/orders` | | `GET` | `/v1/orders` | | `GET` | `/v1/orders/{id}` | | `POST` | `/v1/orders/{id}/cancel` | | `POST` | `/v1/orders/cancel_all` | ### Smart execution | Method | Path | | ------ | ------------------------------------------ | | `POST` | `/v1/complex_orders` | | `POST` | `/v1/complex_orders/preview` | | `GET` | `/v1/complex_orders` | | `GET` | `/v1/complex_orders/{id}` | | `GET` | `/v1/complex_orders/{id}/children` | | `GET` | `/v1/complex_orders/{id}/execution_report` | | `POST` | `/v1/complex_orders/{id}/cancel` | ### Guardrails | Method | Path | | ------------- | --------------------------------- | | `GET` / `PUT` | `/v1/risk_limits` | | `GET` / `PUT` | `/v1/risk_limits/{subaccount_id}` | ### Risk, P\&L & reporting | Method | Path | | ------ | -------------------------------- | | `GET` | `/v1/risk/stats` | | `GET` | `/v1/risk/stats/{subaccount_id}` | | `GET` | `/v1/risk/pnl_history` | | `GET` | `/v1/positions` | | `GET` | `/v1/fills` | | `GET` | `/v1/portfolio` | | `GET` | `/v1/receipts` | | `GET` | `/v1/analytics/execution` | Trading through an AI agent instead? The same operations are exposed as tools on the hosted MCP server at `https://mcp.trymithril.com/mcp`. # Get portfolio Source: https://docs.trymithril.com/api-reference/portfolio/get-portfolio /api-reference/openapi.json get /v1/portfolio # List positions Source: https://docs.trymithril.com/api-reference/positions/list-positions /api-reference/openapi.json get /v1/positions # List execution receipts Source: https://docs.trymithril.com/api-reference/receipts/list-execution-receipts /api-reference/openapi.json get /v1/receipts # Get subaccount risk limits Source: https://docs.trymithril.com/api-reference/risk-limits/get-subaccount-risk-limits /api-reference/openapi.json get /v1/risk_limits/{subaccount_id} # Get workspace risk limits Source: https://docs.trymithril.com/api-reference/risk-limits/get-workspace-risk-limits /api-reference/openapi.json get /v1/risk_limits # Update subaccount risk limits Source: https://docs.trymithril.com/api-reference/risk-limits/update-subaccount-risk-limits /api-reference/openapi.json put /v1/risk_limits/{subaccount_id} # Update workspace risk limits Source: https://docs.trymithril.com/api-reference/risk-limits/update-workspace-risk-limits /api-reference/openapi.json put /v1/risk_limits # Get account risk statistics Source: https://docs.trymithril.com/api-reference/risk/get-account-risk-statistics /api-reference/openapi.json get /v1/risk/stats/{subaccount_id} # Get daily realized P&L history Source: https://docs.trymithril.com/api-reference/risk/get-daily-realized-p&l-history /api-reference/openapi.json get /v1/risk/pnl_history # Get portfolio risk statistics Source: https://docs.trymithril.com/api-reference/risk/get-portfolio-risk-statistics /api-reference/openapi.json get /v1/risk/stats # Create subaccount Source: https://docs.trymithril.com/api-reference/subaccounts/create-subaccount /api-reference/openapi.json post /v1/subaccounts # Delete exchange credentials Source: https://docs.trymithril.com/api-reference/subaccounts/delete-exchange-credentials /api-reference/openapi.json delete /v1/subaccounts/{id}/credentials/{exchange} # Delete subaccount Source: https://docs.trymithril.com/api-reference/subaccounts/delete-subaccount /api-reference/openapi.json delete /v1/subaccounts/{id} # Get subaccount Source: https://docs.trymithril.com/api-reference/subaccounts/get-subaccount /api-reference/openapi.json get /v1/subaccounts/{id} # Get subaccount balances Source: https://docs.trymithril.com/api-reference/subaccounts/get-subaccount-balances /api-reference/openapi.json get /v1/subaccounts/{id}/balances # List subaccounts Source: https://docs.trymithril.com/api-reference/subaccounts/list-subaccounts /api-reference/openapi.json get /v1/subaccounts # Set exchange credentials Source: https://docs.trymithril.com/api-reference/subaccounts/set-exchange-credentials /api-reference/openapi.json put /v1/subaccounts/{id}/credentials # Health check Source: https://docs.trymithril.com/api-reference/system/health-check /api-reference/openapi.json get /health # Create workspace Source: https://docs.trymithril.com/api-reference/workspaces/create-workspace /api-reference/openapi.json post /v1/workspaces # Authentication Source: https://docs.trymithril.com/authentication How the gateway authenticates your requests. Every request to `https://api.trymithril.com` is authenticated with a **bearer API key** in the `Authorization` header: ``` Authorization: Bearer mk_live_xxxxxxxxxxxxxxxxxxxxxxxx ``` The public gateway validates the key, applies your [rate limits](/concepts/rate-limits), and forwards the request to Mithril's core over a private network. Your key never leaves Mithril, and your **exchange** credentials are never sent by you at all — they're attached once in the dashboard and stay encrypted. ## Key types Live keys place real orders with real money against your attached venue credentials. Test keys scope to a test environment for wiring up your integration without touching live venues. Keys are created and revoked on the [API keys](https://app.trymithril.com/keys) page. The full secret is shown **once** at creation — Mithril stores only a SHA-256 hash and can never display it again. Rotate or revoke a key any time; a revoked key returns `401` immediately. ## Managing keys programmatically ```bash theme={null} # Revoke a key (dashboard-authenticated) curl -X DELETE https://api.trymithril.com/v1/api_keys/key_123 \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` Treat an `mk_live_` key like a trading credential. Anyone with it can place orders within your risk limits. Store it in a secret manager or environment variable — **never** commit it to source control. If a key leaks, revoke it in the dashboard right away. ## What a missing or bad key returns ```json theme={null} { "error": { "code": "unauthorized", "message": "missing or invalid API key", "request_id": "req_..." } } ``` See [Errors](/concepts/errors) for the full error contract. # Conventions Source: https://docs.trymithril.com/concepts/conventions Base URL, IDs, units, pagination — the shared rules across every endpoint. ## Base URL ``` https://api.trymithril.com ``` All endpoints live under `/v1`. Requests and responses are JSON with `snake_case` fields. ## Resource IDs Every resource has a prefixed, opaque string ID. The prefix tells you the type: | Prefix | Resource | | ------- | ------------------------------ | | `ws_` | Workspace | | `sub_` | Subaccount | | `key_` | API key | | `mkt_` | Market (unified across venues) | | `ord_` | Order | | `fill_` | Fill | | `pos_` | Position | The `mkt_` identifier is **venue-agnostic**: the same market ID maps the same event across Kalshi and Polymarket, so search, quote, and trade need no per-exchange plumbing. To trade a specific outcome you also pass a `token_id`, which you read from the market's orderbook. ## Units Prices and quantities are passed as **strings**, not numbers, to avoid floating-point precision loss on money. * **Price** — a probability in the range `(0, 1]`. `"0.40"` means 40¢ / 40% implied probability. Mithril normalizes venue conventions (Kalshi cents, Polymarket 0–1) to this single scale. * **Quantity** — a decimal number of shares/contracts, e.g. `"5"` or `"12.5"`. * **Action** — `"buy"` or `"sell"`. * **Side** — the outcome, `"yes"` or `"no"`. ## Pagination List endpoints return a cursor envelope: ```json theme={null} { "data": [ /* ...items... */ ], "next_cursor": "eyJ...", "has_more": true } ``` Pass `?cursor=` to fetch the next page and `?limit=` to set page size (default `50`, max `200`). When `has_more` is `false`, you've reached the end. ```bash theme={null} curl "https://api.trymithril.com/v1/fills?limit=100&cursor=eyJ..." \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` ## Timestamps All timestamps are RFC 3339 / ISO 8601 in UTC, e.g. `2026-07-16T14:30:00Z`. # Errors Source: https://docs.trymithril.com/concepts/errors The single error envelope and what each status means. Every error — from the gateway or from Mithril's core — renders as one shape: ```json theme={null} { "error": { "code": "risk_limit_exceeded", "message": "order notional 40000 exceeds max_order_notional 250", "request_id": "req_9f3a..." } } ``` * **`code`** — a stable, machine-readable string you can branch on. * **`message`** — a human-readable explanation. Safe to log and show. * **`request_id`** — include this when you contact support; it ties your request to our logs. ## Status codes | Status | Meaning | Typical `code` | | ------ | -------------------------------------------------- | ---------------------------- | | `400` | Malformed request or missing required field/header | `bad_request` | | `401` | Missing, invalid, or revoked API key | `unauthorized` | | `403` | Authenticated but not allowed | `forbidden` | | `404` | Resource not found (or not in your workspace) | `not_found` | | `409` | Conflict — e.g. a guardrail rejection | `risk_limit_exceeded` | | `422` | Semantically invalid (e.g. price out of range) | `invalid_argument` | | `429` | Rate limited — back off and retry | `rate_limited` | | `5xx` | Upstream/venue failure | `internal`, `upstream_error` | A guardrail rejection is a **normal, expected** response, not a bug. It means Mithril protected you — the order never reached the venue. See [Guardrails](/guides/guardrails). ## Handling errors ```python theme={null} resp = s.post(f"{BASE}/v1/orders", headers=idem, json=body) if not resp.ok: err = resp.json()["error"] if err["code"] == "risk_limit_exceeded": # tighten size or raise the limit — this is a guardrail doing its job ... else: raise RuntimeError(f"[{resp.status_code}] {err['message']} ({err['request_id']})") ``` # Idempotency Source: https://docs.trymithril.com/concepts/idempotency Make order placement safe to retry. Network calls fail halfway. A timeout doesn't tell you whether your order reached the exchange. To make retries safe, `POST /v1/orders` (and `POST /v1/complex_orders`) **require an `idempotency-key` header**. ``` idempotency-key: 3f9d1c2a-7b6e-4a1f-9c2d-8e5b0a1f2c3d ``` Send a unique key (a UUID is ideal) per logical order. If the same key arrives again — because you retried after a timeout — Mithril returns the **original** order instead of placing a second one. ```bash cURL theme={null} curl -X POST https://api.trymithril.com/v1/orders \ -H "Authorization: Bearer $MITHRIL_API_KEY" \ -H "Content-Type: application/json" \ -H "idempotency-key: $(uuidgen)" \ -d '{ "subaccount_id": "sub_...", "market_id": "mkt_...", "token_id": "...", "action": "buy", "order_type": "limit", "quantity": "5", "price": "0.40" }' ``` ```python Python theme={null} import uuid def place(order_body): return s.post( f"{BASE}/v1/orders", headers={"idempotency-key": str(uuid.uuid4())}, json=order_body, ).json() ``` Reuse the **same** key when retrying the **same** order. Generating a fresh key on retry defeats the protection and can place a duplicate. ## Rules * Scope: keys are scoped to your workspace and the request path. * A request without the header is rejected with `400` before it's forwarded. * Idempotency covers order **placement**. Cancellation is naturally idempotent — cancelling an already-cancelled order is a no-op. # Rate limits Source: https://docs.trymithril.com/concepts/rate-limits How the gateway paces requests, and how to handle 429s. The gateway rate-limits per API key. Limits are split into two classes so that reads never starve your ability to place and cancel orders: | Class | Endpoints | Notes | | --------- | ------------------------------------------------------ | -------------------------------- | | **Read** | `GET` market data, positions, fills, risk stats | Higher ceiling | | **Write** | `POST`/`PUT`/`DELETE` — orders, cancels, limit changes | Lower ceiling; the critical path | Mithril also absorbs each **venue's** own limits server-side (Polymarket's opaque Cloudflare pacing, Kalshi's tiered token buckets), so you code against one predictable ceiling instead of two moving ones. ## When you're limited A throttled request returns `429` with the standard [error envelope](/concepts/errors): ```json theme={null} { "error": { "code": "rate_limited", "message": "rate limit exceeded", "request_id": "req_..." } } ``` Back off and retry. A simple exponential backoff with jitter is enough: ```python theme={null} import time, random def with_backoff(fn, tries=5): for i in range(tries): resp = fn() if resp.status_code != 429: return resp time.sleep(min(2 ** i, 8) + random.random()) return resp ``` Prioritize cancels over new orders in your own client, and prefer [worked orders](/guides/smart-execution) over hand-rolled cancel/replace loops — Mithril's execution engine paces child orders within venue limits for you. Need higher throughput for a market-making strategy? [Talk to us](https://cal.com/karl-mithril/demo) — limits are lifted per desk. # Accounts Source: https://docs.trymithril.com/guides/accounts Workspaces, subaccounts, and unified balances. Mithril's tenancy has three levels: * **Workspace** — your organization. Created automatically on signup. * **Subaccount** — an isolated strategy or client, each with its own attached exchange credentials, positions, and [risk limits](/guides/guardrails). * **Credentials** — your Kalshi API key or Polymarket wallet key, attached to a subaccount, envelope-encrypted, used only to sign orders. Isolating strategies in subaccounts means a runaway bot in one can't touch the capital or limits of another. ## List subaccounts Most calls take a `subaccount_id`. Discover yours instead of hardcoding it: ```bash cURL theme={null} curl https://api.trymithril.com/v1/subaccounts \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` ```python Python theme={null} subs = s.get(f"{BASE}/v1/subaccounts").json()["data"] sub_id = subs[0]["id"] ``` A subaccount (`SubaccountView`): ```json theme={null} { "data": [ { "id": "sub_wdzt3wugmlu4kadia7nuc2dz", "workspace_id": "ws_kit2532bcugmo2opqqxrkb7p", "name": "main", "created_at": "2026-07-16T14:30:00Z" } ], "next_cursor": null, "has_more": false } ``` ## Unified balances `GET /v1/subaccounts/{id}/balances` returns the full, live balance set in one page — normalized across venues (USDC on Polymarket, USD on Kalshi): ```bash cURL theme={null} curl https://api.trymithril.com/v1/subaccounts/sub_.../balances \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` ```python Python theme={null} bal = s.get(f"{BASE}/v1/subaccounts/{sub_id}/balances").json()["data"] for b in bal: print(b["asset"], b["available"], b["total"]) ``` Each balance (`BalanceView`): ```json theme={null} { "data": [ { "asset": "USDC", "total": "1042.50", "available": "1042.50" } ], "has_more": false } ``` ## Create a subaccount `POST /v1/subaccounts` seeds the standard guardrails by default. Set `disable_guardrails: true` to opt out of all protection. ```bash theme={null} curl -X POST https://api.trymithril.com/v1/subaccounts \ -H "Authorization: Bearer $MITHRIL_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "momentum-bot", "disable_guardrails": false }' ``` ## Attach exchange credentials `PUT /v1/subaccounts/{id}/credentials`. The body depends on the venue — but `private_key` is always **write-only** and never returned by any endpoint. ```json Polymarket theme={null} { "exchange": "polymarket", "wallet_address": "0xabc...", "private_key": "0x...", "public_fields": {} } ``` ```json Kalshi theme={null} { "exchange": "kalshi", "api_key_id": "a1b2c3d4-...", "private_key": "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----", "public_fields": {} } ``` `polymarket` or `kalshi`. Polymarket: your wallet address (the signing identity). Kalshi: your API key ID; `private_key` is its PEM-encoded RSA key. Write-only signing secret. Envelope-encrypted at rest, decrypted only in memory to sign an order, never logged, never returned. Credentials are write-only. Once attached they are never returned by any endpoint — every secret field is redacted in responses. Find markets and read the book before you trade. # Guardrails Source: https://docs.trymithril.com/guides/guardrails Server-side risk limits checked before any order reaches the venue. Neither Kalshi nor Polymarket gives you a max order size, a daily-loss limit, or a kill switch. Mithril checks **every** order against your limits **before** it's signed and sent — a rejection means the order never reached the exchange. ## The limits Set at the workspace level and optionally overridden per subaccount (the effective limit is the tighter of the two): | Limit | Enforces | | ------------------------- | ------------------------------------------------- | | `max_order_notional` | Largest single order, in quote currency | | `max_position_per_market` | Cap on exposure to one market | | `max_total_notional` | Cap on total open exposure | | `slippage_bps` | Worst execution slippage tolerated | | `max_concentration_bps` | Cap on how concentrated one position can be | | `max_open_orders` | Ceiling on resting orders | | `max_daily_loss` | Circuit breaker on realized loss for the day | | `kill_switch` | When `true`, rejects **all** new orders instantly | ## Read your limits ```bash cURL theme={null} curl https://api.trymithril.com/v1/risk_limits/sub_... \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` ```python Python theme={null} limits = s.get(f"{BASE}/v1/risk_limits/{sub_id}").json() print(limits["max_order_notional"], limits["kill_switch"]) ``` ```json theme={null} { "id": "rl_...", "workspace_id": "ws_...", "subaccount_id": "sub_...", "max_order_notional": "250", "max_position_per_market": "1000", "max_total_notional": "5000", "slippage_bps": 300, "max_concentration_bps": 4000, "max_open_orders": 20, "max_daily_loss": "1000", "kill_switch": false, "created_at": "2026-07-16T14:00:00Z", "updated_at": "2026-07-16T14:30:00Z" } ``` Notional fields are decimal strings; `"0"` (or an omitted field) means **unlimited**. The `PUT` body accepts the same fields — `max_order_notional`, `max_position_per_market`, `max_total_notional`, `slippage_bps`, `max_concentration_bps`, `max_open_orders`, `max_daily_loss`, `kill_switch`. ## Update a limit ```bash theme={null} curl -X PUT https://api.trymithril.com/v1/risk_limits/sub_... \ -H "Authorization: Bearer $MITHRIL_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "max_order_notional": "250", "max_daily_loss": "1000" }' ``` ## The kill switch Flip one boolean to halt trading on a subaccount — nothing new gets through until you flip it back: ```bash theme={null} curl -X PUT https://api.trymithril.com/v1/risk_limits/sub_... \ -H "Authorization: Bearer $MITHRIL_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "kill_switch": true }' ``` ## What a rejection looks like Submit something over your limit and the order is refused with `409` and a clear reason — this is the guardrail doing its job: ```json theme={null} { "error": { "code": "risk_limit_exceeded", "message": "order notional 40000 exceeds max_order_notional 250", "request_id": "req_..." } } ``` This is exactly what `python 03_guardrails.py` demonstrates — it submits a deliberately oversized order and prints the rejection. Place, track, and cancel — now that the guardrails are set. # Market data Source: https://docs.trymithril.com/guides/market-data Search markets, read the orderbook, pull prices — normalized across venues. Market data is one normalized plane across Kalshi and Polymarket: prices are probabilities in `(0, 1)`, books are unified, and one `mkt_` ID maps the same event on both venues. ## Search markets Discovery is search-driven. Pass a `query` (and optional `limit`): ```bash cURL theme={null} curl "https://api.trymithril.com/v1/markets?query=world%20cup&limit=5" \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` ```python Python theme={null} mkts = s.get(f"{BASE}/v1/markets", params={"query": "world cup", "limit": 5}).json()["data"] market = mkts[0] print(market["id"], market.get("question")) ``` Each result (`MarketView`) in the `data` array: ```json theme={null} { "id": "mkt_...", "exchange": "polymarket", "exchange_market_id": "0x...", "question": "Will Argentina win the World Cup?", "outcomes": [ { "token_id": "7194...", "label": "Yes", "price": "0.42" }, { "token_id": "1088...", "label": "No", "price": "0.58" } ], "status": "open", "close_time": "2026-12-18T00:00:00Z", "volume_24h": "48210.00", "resolved": false } ``` ## Read the orderbook The orderbook gives you a tradable `token_id` (which outcome you're buying) plus live depth: ```bash cURL theme={null} curl https://api.trymithril.com/v1/markets/mkt_.../orderbook \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` ```python Python theme={null} ob = s.get(f"{BASE}/v1/markets/{market['id']}/orderbook").json() token_id = ob["token_id"] best_bid = float(ob["bids"][0]["price"]) if ob["bids"] else 0.0 best_ask = float(ob["asks"][0]["price"]) if ob["asks"] else 1.0 print(f"bid {best_bid:.3f} / ask {best_ask:.3f} spread {best_ask - best_bid:.3f}") ``` The orderbook (`OrderbookView`) — bids and asks are `{price, size}` levels: ```json theme={null} { "market_id": "mkt_...", "token_id": "7194...", "bids": [ { "price": "0.41", "size": "1200" }, { "price": "0.40", "size": "3400" } ], "asks": [ { "price": "0.43", "size": "900" }, { "price": "0.44", "size": "2600" } ] } ``` ## Prices and history | Endpoint | Returns | | -------------------------------- | --------------------------------------------------- | | `GET /v1/markets/{id}` | Full market detail | | `GET /v1/markets/{id}/orderbook` | Live L2 book + `token_id` | | `GET /v1/markets/{id}/prices` | Recent price series | | `POST /v1/markets/match` | Map an event to its equivalent `mkt_` across venues | ```bash theme={null} curl "https://api.trymithril.com/v1/markets/mkt_.../prices?limit=50" \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` `GET /v1/markets/{id}/prices` returns a `PricesView`: ```json theme={null} { "market_id": "mkt_...", "token_id": "7194...", "interval": "1h", "points": [ { "timestamp": "2026-07-16T13:00:00Z", "price": "0.41" } ] } ``` `POST /v1/markets/match` takes `{ "exchange": "kalshi", "exchange_market_id": "..." }` and returns the unified `mkt_` market, creating the mapping on first sight. Market data today is served over REST. If you need the freshest book, poll the orderbook endpoint; the [smart execution](/guides/smart-execution) engine reads live depth for you when working an order. Set the limits every order is checked against before you place one. # Orders Source: https://docs.trymithril.com/guides/orders Place, track, and cancel orders through one API. `POST /v1/orders` is the canonical trade. Mithril risk-checks it, signs it with your attached venue credentials, submits it, and maps the venue's response to one status model. ## Place an order ```bash cURL theme={null} curl -X POST https://api.trymithril.com/v1/orders \ -H "Authorization: Bearer $MITHRIL_API_KEY" \ -H "Content-Type: application/json" \ -H "idempotency-key: $(uuidgen)" \ -d '{ "subaccount_id": "sub_...", "market_id": "mkt_...", "token_id": "7194...", "action": "buy", "order_type": "limit", "quantity": "5", "price": "0.40" }' ``` ```python Python theme={null} import uuid order = s.post( f"{BASE}/v1/orders", headers={"idempotency-key": str(uuid.uuid4())}, json={ "subaccount_id": sub_id, "market_id": market["id"], "token_id": token_id, "action": "buy", "order_type": "limit", "quantity": "5", "price": "0.40", }, ).json() print(order["id"], order["status"]) ``` ### Request fields Which subaccount (and its credentials + limits) to trade under. The unified `mkt_` market identifier. The outcome token to trade, read from the market's orderbook. `buy` or `sell`. `limit` or `market`. Decimal number of shares, as a string (e.g. `"5"`). Limit price — a probability in `(0, 1]` as a string. Required for `limit` orders. The `idempotency-key` header is **required**. See [Idempotency](/concepts/idempotency). ### Response Both placing and fetching an order return the same `OrderView`: ```json theme={null} { "id": "ord_...", "subaccount_id": "sub_...", "exchange": "polymarket", "market_id": "mkt_...", "token_id": "7194...", "side": "yes", "action": "buy", "order_type": "limit", "quantity": "5", "price": "0.40", "status": "open", "traded_qty": "0", "average_price": "0", "fees_paid": "0", "remaining_qty": "5", "external_ref": "0xabc...", "created_at": "2026-07-16T14:30:00Z", "updated_at": "2026-07-16T14:30:01Z", "submitted_at": "2026-07-16T14:30:01Z" } ``` Lifecycle state — see the table below. Filled and outstanding size. Weighted average fill price so far. Present only when `status` is `rejected` — e.g. a guardrail message. ## Track an order ```bash cURL theme={null} curl https://api.trymithril.com/v1/orders/ord_... \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` ```python Python theme={null} order = s.get(f"{BASE}/v1/orders/{order['id']}").json() print(order["status"]) ``` ### Order statuses | Status | Meaning | | ----------- | ------------------------------------------- | | `submitted` | Sent to the venue, awaiting acknowledgement | | `open` | Resting on the book | | `partial` | Partially filled, remainder resting | | `filled` | Fully filled | | `cancelled` | Cancelled (by you or the venue) | | `rejected` | Refused by a guardrail or the venue | ## Cancel ```bash cURL theme={null} # Cancel one curl -X POST https://api.trymithril.com/v1/orders/ord_.../cancel \ -H "Authorization: Bearer $MITHRIL_API_KEY" # Cancel everything on a subaccount curl -X POST https://api.trymithril.com/v1/orders/cancel_all \ -H "Authorization: Bearer $MITHRIL_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "subaccount_id": "sub_..." }' ``` ```python Python theme={null} s.post(f"{BASE}/v1/orders/{order['id']}/cancel") ``` A cancel only marks the order terminal once the venue confirms — so the API never reports a cancellation that didn't actually happen. ## List orders ```bash theme={null} curl "https://api.trymithril.com/v1/orders?limit=50" \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` Work large orders into thin books instead of clipping the print. # Risk & P&L Source: https://docs.trymithril.com/guides/risk Exposure, P&L, fills, and portfolio — one call each, per subaccount or workspace. Ask a prediction-market trader their exposure to one event and most reach for a spreadsheet. Mithril answers directly — per subaccount or across the whole workspace, with venues netted into one view. ## Risk statistics ```bash cURL theme={null} # Per subaccount curl https://api.trymithril.com/v1/risk/stats/sub_... \ -H "Authorization: Bearer $MITHRIL_API_KEY" # Workspace-wide curl https://api.trymithril.com/v1/risk/stats \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` ```python Python theme={null} stats = s.get(f"{BASE}/v1/risk/stats/{sub_id}").json() print(stats["gross_exposure"], stats["unrealized_pnl"], stats["largest_position_pct_bps"]) ``` ```json theme={null} { "workspace_id": "ws_...", "subaccount_id": "sub_...", "gross_exposure": "1840.00", "market_value": "1902.50", "marks_stale": false, "unrealized_pnl": "62.50", "realized_pnl_today": "18.20", "realized_pnl_total": "412.90", "open_order_count": 3, "resting_notional": "250.00", "position_count": 7, "market_count": 5, "largest_position_pct_bps": 3200, "per_market_exposure": [ { "market_id": "mkt_...", "exposure": "588.00", "pct_bps": 3200 } ], "limit_utilization": { "max_total_notional": { "limit": "5000", "used": "1840.00", "pct_bps": 3680 } }, "kill_switch": false, "as_of": "2026-07-16T14:32:00Z" } ``` Percentages are in **basis points** (`largest_position_pct_bps: 3200` = 32%). `marks_stale: true` warns that mark prices couldn't be refreshed, so mark-to-market values are best-effort. ## Daily P\&L history ```bash theme={null} curl https://api.trymithril.com/v1/risk/pnl_history \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` ```json theme={null} { "workspace_id": "ws_...", "subaccount_id": "sub_...", "days": 30, "points": [ { "date": "2026-07-16", "realized_pnl": "18.20", "fees": "1.05", "volume": "540.00", "fill_count": 6, "cumulative_realized_pnl": "412.90" } ], "total_realized_pnl": "412.90", "total_fees": "27.40", "total_volume": "18240.00", "total_fills": 214, "as_of": "2026-07-16T14:32:00Z" } ``` ## Fills Every execution, newest first — with fees computed from each venue's schedule: ```bash cURL theme={null} curl "https://api.trymithril.com/v1/fills?limit=50" \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` ```python Python theme={null} fills = s.get(f"{BASE}/v1/fills", params={"limit": 50}).json()["data"] for f in fills: print(f["side"], f["quantity"], "@", f["price"], "fee", f["fee"]) ``` Each fill (`FillView`): ```json theme={null} { "id": "fill_...", "subaccount_id": "sub_...", "order_id": "ord_...", "exchange": "polymarket", "market_id": "mkt_...", "token_id": "7194...", "side": "yes", "action": "buy", "price": "0.43", "quantity": "125", "fee": "1.07", "realized_pnl": "0", "created_at": "2026-07-16T14:30:05Z" } ``` ## Positions and portfolio `GET /v1/positions` returns a paginated list of `PositionView`: ```json theme={null} { "data": [ { "id": "pos_...", "subaccount_id": "sub_...", "exchange": "polymarket", "market_id": "mkt_...", "token_id": "7194...", "side": "yes", "quantity": "125", "cost_basis": "53.75", "avg_price": "0.43", "mark_price": "0.44", "marked_at": "2026-07-16T14:32:00Z", "created_at": "2026-07-16T14:30:05Z", "updated_at": "2026-07-16T14:32:00Z" } ], "has_more": false } ``` `GET /v1/portfolio` aggregates positions for a scope (`PortfolioView`): ```json theme={null} { "workspace_id": "ws_...", "subaccount_id": "sub_...", "position_count": 7, "total_cost_basis": "1840.00", "positions": [ /* ...PositionView... */ ] } ``` Mark-to-market value and P\&L live on [risk stats](#risk-statistics); the portfolio view is positions + aggregate cost basis. Two more reporting endpoints: | Endpoint | Returns | | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `GET /v1/receipts` | Execution receipts (arrival vs achieved vs naive), one per worked order | | `GET /v1/analytics/execution` | Predicted-vs-realized analytics per fill: `arrival_mid`, `predicted_avg`, `realized_avg`, `slippage_bps`, `prediction_error_bps` | ```bash theme={null} curl https://api.trymithril.com/v1/portfolio \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` `python 06_risk.py` walks all of these in one run — a good template for a monitoring dashboard or an end-of-day report. Every path, method, and auth requirement. # Smart execution Source: https://docs.trymithril.com/guides/smart-execution Preview impact, work orders into thin books, and measure every fill. Prediction-market books are thin — a large marketable order clips the print and attracts adverse selection. Neither venue offers iceberg, TWAP, or pegged orders. Mithril's execution engine does: preview the impact of an order, then let Mithril **work** it under a slippage cap and hand you a transaction-cost report at the end. ## Preview impact before you trade `POST /v1/complex_orders/preview` estimates fillable size and average price against live depth, and recommends a strategy: ```bash cURL theme={null} curl -X POST https://api.trymithril.com/v1/complex_orders/preview \ -H "Authorization: Bearer $MITHRIL_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "market_id": "mkt_...", "token_id": "...", "action": "buy", "quantity": "500" }' ``` ```python Python theme={null} preview = s.post(f"{BASE}/v1/complex_orders/preview", json={ "market_id": market["id"], "token_id": token_id, "action": "buy", "quantity": "500", }).json() print(preview["impact"]["fillable_qty"], preview["impact"]["avg_price"]) print(preview["recommended_plan"]["strategy"], "—", preview["recommended_plan"]["reason"]) ``` The response makes the walk-the-book impact and the fee trade-off explicit — crossing pays the taker fee, resting earns the maker rebate: ```json theme={null} { "impact": { "action": "buy", "requested_qty": "500", "fillable_qty": "500", "avg_price": "0.436", "worst_price": "0.45", "mid": "0.42", "notional_cost": "218.00", "slippage_bps": 380, "levels_consumed": 4, "complete": true }, "recommended_plan": { "strategy": "iceberg", "clip_qty": "125", "slices": 4, "reason": "size exceeds top-of-book; work it in clips as liquidity refills" }, "fee_rate": 0.02, "taker": { "taker_fee": "4.36", "maker_rebate": "0", "all_in_avg_price": "0.445", "all_in_cost": "222.36", "fee_bps": 200 }, "maker": { "taker_fee": "0", "maker_rebate": "2.18", "all_in_avg_price": "0.432", "all_in_cost": "215.82", "fee_bps": 0 } } ``` `fillable_qty`, `avg_price`, and `slippage_bps` live under the **`impact`** object; `recommended_plan` is top-level. ## Strategies | Strategy | Use it when | | ------------- | ----------------------------------------------------------------- | | `smart_taker` | Take liquidity up to a worst price, sweeping only what's cheap | | `iceberg` | Post size in clips so you don't show the whole hand | | `peg` | Rest passively at/inside the spread, repegging within a band | | `adaptive` | "Just get me best execution" — Mithril balances urgency vs impact | ## Work an order Submit a complex order the same way as a plain one — with an `idempotency-key` — choosing a `type` and its params: ```bash cURL theme={null} curl -X POST https://api.trymithril.com/v1/complex_orders \ -H "Authorization: Bearer $MITHRIL_API_KEY" \ -H "Content-Type: application/json" \ -H "idempotency-key: $(uuidgen)" \ -d '{ "subaccount_id": "sub_...", "market_id": "mkt_...", "token_id": "...", "type": "adaptive", "action": "buy", "total_quantity": "500", "adaptive": { "limit_price": "0.62", "urgency": "low", "max_duration_s": 300 } }' ``` ```python Python theme={null} import uuid co = s.post(f"{BASE}/v1/complex_orders", headers={"idempotency-key": str(uuid.uuid4())}, json={ "subaccount_id": sub_id, "market_id": market["id"], "token_id": token_id, "type": "adaptive", "action": "buy", "total_quantity": "500", "adaptive": {"limit_price": "0.62", "urgency": "low", "max_duration_s": 300}, }).json() cid = co["id"] ``` ## Watch it work `GET /v1/complex_orders/{id}/children` returns the plan's child orders with live queue positions: ```json theme={null} { "children": [ { "order_id": "ord_...", "status": "filled", "quantity": "125", "price": "0.43", "traded_qty": "125", "average_price": "0.429", "created_at": "2026-07-16T14:30:05Z" }, { "order_id": "ord_...", "status": "open", "quantity": "125", "price": "0.43", "traded_qty": "0", "average_price": "0", "created_at": "2026-07-16T14:31:10Z", "queue_ahead": "800" } ] } ``` ## Read the execution report (TCA) `GET /v1/complex_orders/{id}/execution_report` is your **receipt**: what you paid versus arrival, versus estimate, versus a naive sweep — measured on your own fills, not claimed. ```json theme={null} { "action": "buy", "total_quantity": "500", "filled_qty": "500", "realized_avg_price": "0.431", "arrival_mid_price": "0.42", "estimated_avg_price": "0.436", "naive_sweep_avg_price": "0.448", "implementation_shortfall_bps": 262, "estimate_error_bps": 50, "realized_fees_paid": "2.15", "realized_all_in_avg_price": "0.435", "naive_sweep_all_in_price": "0.457", "savings_vs_naive": "11.00", "savings_vs_naive_bps": 220, "benchmark_available": true, "children": [ /* ...ChildFillView... */ ] } ``` Quote-currency saved versus sweeping the book naively — your number, measured per fill. `benchmark_available: false` means there wasn't enough book data to compute it. Cancel the remainder any time: ```bash theme={null} curl -X POST https://api.trymithril.com/v1/complex_orders/co_.../cancel \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` Conditional orders (take-profit / stop-loss / stop) are on the roadmap and are rejected at submission today, so you never get a plan that nothing will act on. See the exposure and P\&L those fills produced. # Introduction Source: https://docs.trymithril.com/index Welcome to your project Write a short description of your product here. What it does, who it's for, and what they can accomplish with it. Ready to make this your own? Start by editing this page. Update your `docs.json` file to customize your site. Then fill out the [Quickstart](/quickstart) page. This card links to the quickstart page in your project. Add cards, callouts, steps, tabs, and more to design and structure your pages. Set your site name, branding, and navigation in the `docs.json` file. # Quickstart Source: https://docs.trymithril.com/quickstart From an API key to a risk-checked order in a few minutes. Everything below talks to the public gateway at `https://api.trymithril.com`. The **only** thing you configure is an API key — venue auth, guardrails, and risk accounting happen server-side. ## Get your API key Everything runs off one `mk_live_` key. Here's the path from signup to key, in the [dashboard](https://app.trymithril.com): Sign up at [app.trymithril.com](https://app.trymithril.com) — or [book 20 minutes](https://cal.com/karl-mithril/demo) and we'll onboard you personally. Your workspace is created for you on first sign-in. Beta is free. Starting your plan is what unlocks key creation, so complete this step in onboarding before heading to the keys page. Create a **subaccount**, then attach your Kalshi API key or Polymarket wallet key to it. Credentials are envelope-encrypted and used only to sign your orders — never returned, never logged. On the [API keys](https://app.trymithril.com/keys) page, create an `mk_live_` key. **It's shown once** — copy it into a secret manager or env var right away. (Use `mk_test_` while you wire things up.) Keep the key in `MITHRIL_API_KEY`; every example and the SDK read it from there automatically. ## Two ways to call the gateway The fastest path is the **Python SDK** — it handles auth, venue signing, idempotency, pagination, and typed errors. Or call the REST API directly with any HTTP client. Both talk to the same gateway; the tabs below show each. ```bash theme={null} pip install trymithril # for the SDK export MITHRIL_API_KEY=mk_live_... ``` ## Your first call Confirm you can reach the gateway by listing your subaccounts. ```python SDK theme={null} from trymithril import Mithril m = Mithril() # reads MITHRIL_API_KEY print(m.subaccounts.list()[0].id) ``` ```bash cURL theme={null} curl https://api.trymithril.com/v1/subaccounts \ -H "Authorization: Bearer $MITHRIL_API_KEY" ``` ```python requests theme={null} import os, requests BASE = "https://api.trymithril.com" s = requests.Session() s.headers["Authorization"] = f"Bearer {os.environ['MITHRIL_API_KEY']}" print(s.get(f"{BASE}/v1/subaccounts").json()["data"][0]["id"]) ``` A successful response is Mithril's standard list envelope: ```json theme={null} { "data": [ { "id": "sub_wdzt3wugmlu4kadia7nuc2dz", "name": "main", "workspace_id": "ws_..." } ], "next_cursor": null, "has_more": false } ``` ## Place a risk-checked order The canonical trade is `POST /v1/orders`. Grab a `token_id` from a market's orderbook, then submit. The **`idempotency-key` header** makes a blind retry safe (see [Idempotency](/concepts/idempotency)) — the SDK attaches it for you. ```python SDK theme={null} sub = m.subaccounts.list()[0] market = m.markets.search("world cup", limit=1)[0] ob = m.markets.orderbook(market.id) order = m.orders.create( subaccount_id=sub.id, market_id=market.id, token_id=ob.token_id, action="buy", quantity="5", price="0.40", ) print(order.id, order.status) ``` ```bash cURL theme={null} curl -X POST https://api.trymithril.com/v1/orders \ -H "Authorization: Bearer $MITHRIL_API_KEY" \ -H "Content-Type: application/json" \ -H "idempotency-key: $(uuidgen)" \ -d '{ "subaccount_id": "sub_...", "market_id": "mkt_...", "token_id": "7194...", "action": "buy", "order_type": "limit", "quantity": "5", "price": "0.40" }' ``` ```python requests theme={null} import uuid order = s.post( f"{BASE}/v1/orders", headers={"idempotency-key": str(uuid.uuid4())}, json={ "subaccount_id": "sub_...", "market_id": "mkt_...", "token_id": "7194...", "action": "buy", "order_type": "limit", "quantity": "5", # decimal STRING "price": "0.40", # probability in (0, 1] as a STRING }, ).json() print(order["id"], order["status"]) ``` Prices are probabilities in `(0, 1]` and quantities are decimals — both passed as **strings** to avoid float precision loss. See [Conventions](/concepts/conventions). ## Make it useful for you You have a key and a working call. Here's the path from "hello world" to Mithril running your execution and risk: Before you trade, tell Mithril your limits — max order size, daily-loss circuit breaker, kill switch. Every order is checked against them server-side. See [Guardrails](/guides/guardrails). ```python theme={null} m.risk_limits.update(sub.id, max_order_notional="250", max_daily_loss="1000") ``` Search across both venues and pull the book before you quote or take. See [Market data](/guides/market-data). Vanilla limit/market orders, or hand Mithril size to [work into thin books](/guides/smart-execution) with `iceberg` / `peg` / `adaptive` and get a TCA receipt on every fill. Read exposure, P\&L, and per-market concentration in one call — per subaccount or across the workspace. See [Risk & P\&L](/guides/risk). Give each bot or strategy its own [subaccount](/guides/accounts) — separate credentials, positions, and limits — so one can't touch another's capital. ## Run the full walkthrough The `examples/` folder is a runnable tour of the whole stack — one script per layer, all built on the SDK, the only config an API key: ```bash theme={null} pip install trymithril export MITHRIL_API_KEY=mk_live_... python 01_account.py # subaccounts + balances python 02_market_data.py # search, orderbook, prices python 03_guardrails.py # watch the risk engine reject an oversized order python 04_orders.py --live # limit order lifecycle python 05_smart_execution.py # impact preview + adaptive execution + TCA python 06_risk.py # exposure, P&L, fills, portfolio ``` Typed models, auto-idempotency, pagination, and errors. Set the limits every order is checked against. # MCP server (AI agents) Source: https://docs.trymithril.com/sdks/mcp Let Claude or any MCP agent trade through Mithril — with your risk limits enforced. Mithril runs a hosted [MCP](https://modelcontextprotocol.io) server so an AI agent (Claude, Codex, your own) can use Mithril as tools: search markets, place and cancel orders, read positions/fills/portfolio, and manage risk limits — with every order still risk-checked server-side. It's just another consumer of the public API: it forwards each tool call to the gateway with **your** bearer key and holds no logic or exchange keys of its own. ``` https://mcp.trymithril.com/mcp ``` ## Connect your agent Point your MCP client at the hosted endpoint and pass your Mithril API key as a bearer token — no install, no local binary. Use `mk_test_...` for the sandbox. ```json Config theme={null} { "mcpServers": { "mithril": { "url": "https://mcp.trymithril.com/mcp", "headers": { "Authorization": "Bearer mk_live_your_api_key" } } } } ``` ```bash Claude Code theme={null} claude mcp add mithril --transport http https://mcp.trymithril.com/mcp \ --header "Authorization: Bearer mk_live_your_api_key" ``` ```bash Codex theme={null} codex mcp add mithril https://mcp.trymithril.com/mcp \ --header "Authorization: Bearer mk_live_your_api_key" ``` The key is the same `mk_live_` / `mk_test_` key from the [dashboard](https://app.trymithril.com/keys) you'd use with the REST API or SDK. Each request builds a per-request client from your key — an unauthenticated call never reaches Mithril. ## Tool catalog Sixteen tools, each with a typed schema the agent reads: | Group | Tools | | ----------- | --------------------------------------------------------------------------------- | | **Markets** | `search_markets`, `get_market`, `get_orderbook`, `get_prices` | | **Trading** | `place_order`, `cancel_order`, `cancel_all_orders`, `list_orders`, `get_order` | | **Account** | `get_positions`, `get_fills`, `get_portfolio`, `get_balances`, `list_subaccounts` | | **Risk** | `get_risk_limits`, `set_risk_limits` | `place_order` attaches an idempotency key automatically. `cancel_all_orders` is a one-call kill switch. Because the same [guardrails](/guides/guardrails) apply, an agent physically can't place an order outside the limits you set — `set_risk_limits` and a low `max_order_notional` are your seatbelt for autonomous trading. Give an agent an `mk_test_` key first and watch it trade the sandbox before handing it a live key with tight limits. ## Local (stdio) mode Prefer to run it yourself? The server also speaks stdio, taking a single key from `MITHRIL_API_KEY`: ```json theme={null} { "mcpServers": { "mithril": { "command": "/absolute/path/to/mithril-mcp", "env": { "MCP_TRANSPORT": "stdio", "MITHRIL_API_KEY": "mk_live_your_key" } } } } ``` The limits an agent trades within. # Python SDK Source: https://docs.trymithril.com/sdks/python The official Python client for Mithril — typed, batteries-included. The Python SDK wraps the gateway so you write trading logic, not HTTP. It handles auth, venue signing, idempotency keys, pagination, retries, and typed [Pydantic](https://docs.pydantic.dev) responses. The only configuration is an API key. ## Installation ```bash pip theme={null} pip install trymithril ``` ```bash uv theme={null} uv add trymithril ``` ## Quick start ```python theme={null} from trymithril import Mithril client = Mithril() # reads MITHRIL_API_KEY from the environment # Discover your subaccount — no IDs to hardcode sub = client.subaccounts.list()[0] # Find a market and read the book market = client.markets.search("world cup", limit=1)[0] book = client.markets.orderbook(market.id) # Place a risk-checked order (idempotency key generated for you) order = client.orders.create( subaccount_id=sub.id, market_id=market.id, token_id=book.token_id, action="buy", quantity="5", price="0.40", ) print(order.id, order.status) ``` Your exchange credentials never touch the SDK — you attach them once in the dashboard, and Mithril signs orders server-side. The SDK only ever holds your `mk_live_` / `mk_test_` key. ## The client ```python theme={null} from trymithril import Mithril client = Mithril( api_key="mk_live_...", # or MITHRIL_API_KEY base_url="https://api.trymithril.com", # or MITHRIL_BASE_URL timeout=15.0, max_retries=2, # retries on 429 ) ``` Every resource hangs off the client: `client.subaccounts`, `client.markets`, `client.orders`, `client.complex_orders`, `client.risk_limits`, `client.risk`, `client.positions`, `client.fills`, `client.portfolio`, `client.receipts`, `client.analytics`. ## Subaccounts Subaccounts isolate strategies — each with its own credentials, positions, and [risk limits](#guardrails). Most calls take a `subaccount_id`, so discover it rather than hardcoding. ```python theme={null} subs = client.subaccounts.list() sub = subs[0] print(sub.id, sub.name) # Unified balances across venues (USDC on Polymarket, USD on Kalshi) for bal in client.subaccounts.balances(sub.id): print(bal.asset, bal.available, "/", bal.total) # Create a new strategy subaccount momentum = client.subaccounts.create("momentum-bot") ``` Attach exchange credentials (write-only — never returned): ```python theme={null} # Polymarket client.subaccounts.attach_credentials( sub.id, "polymarket", wallet_address="0x...", private_key="0x...", ) # Kalshi (private_key is the PEM-encoded RSA key) client.subaccounts.attach_credentials( sub.id, "kalshi", api_key_id="a1b2c3d4-...", private_key="-----BEGIN RSA PRIVATE KEY-----\n...", ) ``` ## Market data One normalized data plane across venues — prices are probabilities in `(0, 1)`, and one `mkt_` id maps the same event on both. ```python theme={null} # Search (paginated) markets = client.markets.search("fed rate cut", limit=5) market = markets[0] print(market.question, market.exchange) # The outcome tokens you can trade for outcome in market.outcomes: print(outcome.label, outcome.token_id, outcome.price) # Live order book book = client.markets.orderbook(market.id) best_bid = book.bids[0].price if book.bids else None best_ask = book.asks[0].price if book.asks else None # Price history for point in client.markets.prices(market.id, limit=50).points: print(point.timestamp, point.price) ``` Free-text search across both venues. Filter to `"polymarket"` or `"kalshi"`. Filter by market status (e.g. `"open"`). Page size, max 200. ## Orders Place a limit or market order. Mithril risk-checks it, signs it, submits it, and maps the venue's response to one status model. The `idempotency-key` is attached automatically, so a retry after a timeout never double-places. ```python theme={null} order = client.orders.create( subaccount_id=sub.id, market_id=market.id, token_id=book.token_id, action="buy", # "buy" | "sell" order_type="limit", # "limit" | "market" quantity="5", # decimal string of shares price="0.40", # probability in (0, 1], required for limit ) # Track it order = client.orders.get(order.id) print(order.status, order.traded_qty, "/", order.quantity) # Cancel client.orders.cancel(order.id) client.orders.cancel_all(sub.id) # kill switch for one subaccount ``` Pass your own stable key for end-to-end safe retries across process restarts. Omit it and the SDK generates one per call. Order statuses: `submitted`, `open`, `partial`, `filled`, `cancelled`, `rejected`. A `rejected` order carries a `reject_reason` (often a guardrail). ## Smart execution Thin books punish size. Preview an order's impact, then let Mithril **work** it under a slippage cap and hand you a transaction-cost report. ```python theme={null} preview = client.complex_orders.preview( market_id=market.id, token_id=book.token_id, action="buy", quantity="500", ) print(preview.impact.fillable_qty, "@", preview.impact.avg_price, f"({preview.impact.slippage_bps} bps)") print("recommended:", preview.recommended_plan.strategy, "—", preview.recommended_plan.reason) ``` Create a worked order by choosing a `type` and passing its params. Four strategies: ```python Adaptive theme={null} # "Just get me best execution" — balances urgency vs impact order = client.complex_orders.create( subaccount_id=sub.id, market_id=market.id, token_id=book.token_id, type="adaptive", action="buy", total_quantity="500", adaptive={"limit_price": "0.62", "urgency": "low", "max_duration_s": 300}, ) ``` ```python Iceberg theme={null} # Show a slice at a time so you don't reveal the whole hand order = client.complex_orders.create( subaccount_id=sub.id, market_id=market.id, token_id=book.token_id, type="iceberg", action="buy", total_quantity="500", iceberg={"displayed_qty": "125", "limit_price": "0.62", "reload_delay_s": 2}, ) ``` ```python Peg theme={null} # Rest at/inside the spread, repegging within a band order = client.complex_orders.create( subaccount_id=sub.id, market_id=market.id, token_id=book.token_id, type="peg", action="buy", total_quantity="500", peg={"min_price": "0.55", "max_price": "0.65", "post_only": True}, ) ``` ```python Smart taker theme={null} # Sweep marketable clips only when enough liquidity sits within the limit order = client.complex_orders.create( subaccount_id=sub.id, market_id=market.id, token_id=book.token_id, type="smart_taker", action="buy", total_quantity="500", smart_taker={"limit_price": "0.62", "min_qty": "50"}, ) ``` Watch it work, then read the receipt: ```python theme={null} # Child orders + live queue positions for child in client.complex_orders.children(order.id).children: print(child.status, child.traded_qty, "@", child.average_price) client.complex_orders.cancel(order.id) # cancel the remainder # Transaction-cost analysis: your fills vs arrival, estimate, and a naive sweep report = client.complex_orders.execution_report(order.id) print("saved", report.savings_vs_naive, f"({report.savings_vs_naive_bps} bps)") ``` Conditional orders (take-profit / stop-loss / stop) are on the roadmap and are rejected at submission today, so you never get a plan nothing will act on. ## Guardrails Set the limits every order is checked against — server-side, before it reaches the venue. ```python theme={null} # Read effective limits for a subaccount limits = client.risk_limits.get(sub.id) print(limits.max_order_notional, limits.kill_switch) # Update them (only the fields you pass change) client.risk_limits.update( sub.id, max_order_notional="250", max_daily_loss="1000", slippage_bps=300, ) # Flip the kill switch to halt all new orders on a subaccount client.risk_limits.update(sub.id, kill_switch=True) ``` Fields: `max_order_notional`, `max_position_per_market`, `max_total_notional`, `slippage_bps`, `max_concentration_bps`, `max_open_orders`, `max_daily_loss`, `kill_switch`. Notional fields are decimal strings; `"0"` means unlimited. ## Risk & portfolio One call each for exposure, P\&L, fills, positions, and portfolio — per subaccount or across the whole workspace. ```python theme={null} stats = client.risk.stats(sub.id) # omit the id for workspace-wide print(stats.gross_exposure, stats.unrealized_pnl, stats.largest_position_pct_bps) for point in client.risk.pnl_history().points: print(point.date, point.realized_pnl, point.fees) for fill in client.fills.list(limit=50): print(fill.side, fill.quantity, "@", fill.price, "fee", fill.fee) for pos in client.positions.list(): print(pos.market_id, pos.quantity, "avg", pos.avg_price) pf = client.portfolio.get() print(pf.position_count, "positions, cost basis", pf.total_cost_basis) ``` ## Errors Failed calls raise typed exceptions carrying `code`, `message`, and `request_id`: ```python theme={null} from trymithril import RiskLimitExceeded, RateLimitError, MithrilError try: client.orders.create(...) except RiskLimitExceeded as e: # a guardrail protected you — the order never reached the venue print("blocked:", e.message) except RateLimitError: ... # 429s are already auto-retried; raised only after max_retries except MithrilError as e: print(f"[{e.status}] {e.code}: {e.message} ({e.request_id})") ``` | Exception | Status | When | | --------------------- | --------- | ------------------------------------- | | `AuthenticationError` | 401 | Missing, invalid, or revoked key | | `PermissionError` | 403 | Authenticated but not allowed | | `NotFoundError` | 404 | Resource not in your workspace | | `BadRequestError` | 400 / 422 | Malformed request or invalid argument | | `RiskLimitExceeded` | 409 | A guardrail rejected the order | | `RateLimitError` | 429 | Rate limited (auto-retried first) | | `ServerError` | 5xx | Upstream / venue failure | ## Pagination List endpoints return a `Page` — a list that also carries `.has_more` and `.next_cursor`. Use `.iterate()` to walk every page automatically: ```python theme={null} # One page page = client.fills.list(limit=100) print(len(page), page.has_more, page.next_cursor) # All pages, lazily for fill in client.fills.iterate(): process(fill) ``` `iterate()` is available on `markets`, `orders`, `positions`, and `fills`. ## Responses Responses are Pydantic models — typed attributes, validation, and unknown fields preserved so a new API field never breaks you: ```python theme={null} order.status # typed attribute preview.impact.fillable_qty # nested models order.model_dump() # plain dict when you need one ``` Six scripts — one per stack layer — all built on this SDK.