Skip to main content
Glama

oddsrail

Рельсы, которые ИИ-агенты используют для торговли на предиктивных рынках.

MCP-сервер, который даёт любому агенту (Claude Code, Claude Desktop или любому MCP-совместимому) доступ к предиктивным рынкам на Polymarket и Kalshi: поиск рынков, стаканы заявок, история цен, позиции и маршрутизация ордеров — с ончейн-атрибуцией builder-кода на Polymarket — плюс два премиальных сигнальных инструмента (обнаружение перелёта/затухания в игре, риск разрешения споров).

Бизнес-модель: маршрутизированный поток ордеров приносит builder-комиссии; сигнальные инструменты — платный слой данных (планируется оплата за вызов через x402).

Почему это, а не Parsec

Ближайший конкурент (parsecapi.com) — это закрытый хостинг-сервис: он хранит ваши ключи биржи (или управляет кошельком, который подписывает за вас), а его Builder Program оставляет себе 55–85% комиссий, которые собирают билдеры. oddsrail противоположен по всем параметрам: самохостинг, некастодиальность (ключи никогда не покидают вашу машину), открытый исходный код, и вы сохраняете 100% своих Polymarket builder-комиссий, потому что атрибуция использует нативный механизм Polymarket, а не посреднический эскроу. Parsec также не поставляет никаких сигнальных/аналитических инструментов и ничего по риску разрешения — это наш платный слой.

Related MCP server: telekash-mcp-server

Быстрый старт

Требуется Python 3.11+.

pip install oddsrail
claude mcp add --transport stdio oddsrail -- oddsrail

Или из клона, без установки:

python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
claude mcp add --transport stdio oddsrail -- /abs/path/to/oddsrail/.venv/bin/python -m oddsrail.server

Затем попросите агента: «найди рынки о финале чемпионата мира и запусти сигнал overshoot на фаворита».

Как работает атрибуция (CLOB V2, проверено в августе 2026)

  1. Получите свой builder-код (bytes32) на polymarket.com → Settings → Builders. Установите там свои ставки комиссий: taker до 100 б.п., maker до 50 б.п. — добавляются поверх комиссий платформы и зачисляются на ваш builder-кошелёк.

  2. export ODDSRAIL_BUILDER_CODE=0x... там, где запущен сервер.

  3. Каждый ордер, который любой агент маршрутизирует через place_order, получает код в поле builder структуры ордера V2 до подписания — атрибуция ончейн, видна в каждом событии OrderFilled на CTF Exchange V2.

  4. Проверьте с помощью инструмента builder_stats (публичная конечная точка builder-trades + лидерборд).

Переменные окружения

Variable

Default

Meaning

ODDSRAIL_DRY_RUN

1

1 = ордера симулируются и возвращаются, никогда не публикуются. Установите 0 для торговли.

ODDSRAIL_BUILDER_CODE

unset

Ваш bytes32 builder-код — атрибуция + комиссии.

POLYMARKET_PRIVATE_KEY

unset

Ключ кошелька оператора; требуется только для реальной торговли. Никогда не покидает эту машину.

POLYMARKET_WALLET_ADDRESS

unset

Адрес прокси/депозитного кошелька, если аккаунт использует такой.

Статус — проверено вживую 2026-08-23

Все 10 вызываемых инструментов были прогнаны end-to-end через реальную MCP-клиентскую сессию против живого Polymarket с финского VPS (/opt/oddsrail). Проверено: поиск, просмотр рынка, стакан (9/65 уровней), история цен (361 точка), сигнал overshoot, риск спора, лидерборд билдеров, dry-run ордер, открытые ордера, информация о сервере.

Во время этого прогона сопоставления полей были исправлены по реальному API — формы, угаданные по документации, оказались неверными в трёх местах (outcomes — это словарь с ключами yes/no, search() вкладывает рынки внутрь событий, а данные по стакану/объёму/разрешению находятся в подобъектах prices/metrics/state/resolution).

⚠️ Примечание о сети

Домены API Polymarket заблокированы в турецких сетях (BTK) — локальное тестирование падает на TLS с блокирующей страницей. Запускайте сервер там, где Polymarket доступен (финский VPS в /opt/oddsrail, VPN или любая незаблокированная сеть). Логика сигналов и MCP-слой полностью тестируются офлайн.

Kalshi (площадка №2)

Kalshi — это принеси свой ключ и однопользовательская по дизайну: оператор предоставляет свой собственный API-ключ, торгует на своём аккаунте, и этот сервер ничего не кэширует. Это намеренно — Developer Agreement Kalshi ограничивает использование API только собственной торговлей участника (§3), запрещает содействие торговле других участников (§3.2) и сублицензирование API (§3.7), а также ограничивает хранение/передачу данных API (§3.1). Хостинг-сервис с несколькими арендаторами для Kalshi не соответствовал бы требованиям; самохостинговый — соответствует.

Здесь атрибуции не существует. Kalshi Builder Codes — это интеграция Solana/DFlow/Jupiter — в REST API нет ни одного поля билдера или аффилиата, поэтому поток ордеров Kalshi нельзя атрибутировать или монетизировать так, как на Polymarket. Kalshi в oddsrail для покрытия и охвата сигналов, а не для дохода от маршрутизации.

Две формы в этом API легко перепутать, поэтому oddsrail нормализует обе:

  • Цены — это долларовые строки, а не центы ("0.5600"), размеры — строки с фиксированной точкой ("10.00"); устаревшие поля в целых центах были удалены в марте 2026. Вся арифметика использует Decimal.

  • Стакан заявок состоит только из бидов с обеих сторон. yes_dollars и no_dollars — оба лестницы бидов, по возрастанию — так что лучший бид — это последний элемент, а бид NO по $0.99 есть аск YES по $0.01. kalshi_get_orderbook возвращает обычное представление бид/аск книги YES с лучшими ценами первыми, плюс сырые лестницы.

Размещение ордеров говорит на естественных терминах — outcome (yes/no), action (buy/sell), price = вероятность этого исхода — и внутренне переводит их в bid/ask книги YES Kalshi (покупка NO по 0.25 становится аском по 0.75). Этот перевод покрыт юнит-тестами, так как это очевидное место для бага с инвертированной позицией.

Учётные данные: KALSHI_KEY_ID плюс KALSHI_PRIVATE_KEY_PATH (PKCS#8 PEM) или KALSHI_PRIVATE_KEY. Установите KALSHI_DEMO=1 для работы с демо-средой. Инструментам чтения ключ вообще не нужен.

Инструменты (21)

  • search_markets, get_market, get_orderbook, price_history, get_positions — только чтение, без ключей

  • overshoot_signal — премиум: обнаружение свежих панических скачков + историческая склонность этого рынка к возврату (портировано из анализатора polymarket-wc)

  • dispute_risk — премиум: прозрачная эвристика 0–100 для оспариваемых (склонных к UMA-спорам) разрешений

  • place_order, cancel_order, open_orders — торговля, по умолчанию dry-run

  • builder_stats — проверка атрибуции + публичный лидерборд билдеров

  • server_info — статус конфигурации, по площадкам

Kalshi: kalshi_search_markets, kalshi_get_market, kalshi_get_orderbook, kalshi_get_trades, kalshi_balance, kalshi_positions, kalshi_open_orders, kalshi_place_order, kalshi_cancel_order.

Заметки о стеке

  • Официальный унифицированный SDK polymarket-client (0.6.x): AsyncPublicClient для данных, AsyncSecureClient.place_limit_order(..., builder_code=...) для атрибутированных ордеров. Устаревший py-clob-client архивирован и не может прикреплять builder-коды — не используйте его.

  • MCP SDK 2.0: MCPServer из mcp.server.mcpserver (старый импорт mcp.server.fastmcp.FastMCP исчез в 2.x).

  • Kalshi работает на простых httpx + cryptography, а не на официальном SDK: kalshi-python-sync требует Python >=3.13 и переиздаётся еженедельно в ногу с версией спецификации. Аутентификация — RSA-PSS(SHA256, salt=длина дайджеста) по str(unix_ms) + METHOD + path, где путь включает /trade-api/v2 и исключает строку запроса. Базовый URL теперь external-api.kalshi.com.

  • x402 (планируется): официальный пакет x402 на PyPI (v2.20+) может напрямую оборачивать MCP-инструменты (x402.mcp, оплата едет в _meta вызова инструмента), но его MCP-хелперы сейчас нацелены на mcp 1.x — интеграция означает пиннинг mcp>=1.28,<2 или ожидание релиза, совместимого с 2.x. Для расчётов в mainnet нужен фасилитатор (Coinbase CDP: 1 000 бесплатных расчётов в месяц, затем $0.001). Сохраняйте бесплатные тарифы обоих сигналов, чтобы реестры могли индексировать сервер.

Как выглядит экономика билдеров (вживую, 2026-08-23)

Взято из публичного лидерборда через builder_stats:

weekly

all-time

#1 (betmoar)

$2.31M

$2.10B

медиана топ-25

$127K

$88.2M

вход в топ-25

$42K

$36.8M

Показательные строки — это строки с малым числом пользователей: MagicMarkets маршрутизирует $354K/неделю при 1 активном пользователе, Gate — $1.11M/неделю при 2, PolymarketScan — $277K при 3. Это операторы ботов, маршрутизирующие собственный поток — точный целевой клиент oddsrail — и они показывают, что один серьёзный агент-трейдер стоит реального объёма. Кошельки (MetaMask, 37K пользователей) доминируют по числу пользователей, а не по объёму на пользователя.

Дорожная карта

  1. Живой смоук-тест из незаблокированной сети — сделано 2026-08-23, все инструменты проходят

  2. Зарегистрировать builder-код (polymarket.com → Settings → Builders), установить комиссии 0 б.п. при запуске, экспортировать ODDSRAIL_BUILDER_CODE; первый атрибутированный ордер на крошечный размер

  3. Kalshi как площадка №2 — сделано 2026-08-23, 9 инструментов, проверено вживую

  4. Платная обёртка x402 для двух сигналов, как только разрешится конфликт mcp-2.x

  5. Листинги в реестрах: официальный MCP-реестр (mcp-publisher, маркер mcp-name: на PyPI), Smithery (нужен публичный streamable-HTTP + бесплатный инструмент для их сканера), Glama (glama.json)

Листинг / распространение

  • GitHub: https://github.com/hmesutozsoy/oddsrail (публичный, MIT)

  • Glama: автоматически обходит GitHub; glama.json в корне репозитория заявляет о сопровождении.

  • Официальный MCP-реестр: server.json готов. Для публикации сначала нужен пакет на PyPI (реестр проверяет владение через маркер mcp-name: io.github.hmesutozsoy/oddsrail в README на PyPI), затем mcp-publisher login github && mcp-publisher publish.

  • Smithery: требует публичный HTTPS streamable-HTTP endpoint — доступен, когда oddsrail будет размещён, а не запущен локально через stdio.

Available Tools

42 tools
attribution_ledgerA
Read-onlyIdempotent
Inspect

Attribution ledger for the builder code in use: every trade carrying it, aggregated per Sunday-start week and per wallet, with the maintainer's own wallets split out into an honest 'external' line. Built from Polymarket's own public builder feed, so any figure it reports can be checked at data-api.polymarket.com/v1/builders/leaderboard.

Inputs: no named parameters.

builder_statsA
Read-onlyIdempotent
Inspect

Builder attribution stats: the public builder leaderboard, and (if ODDSRAIL_BUILDER_CODE is set) matched trades attributed to this operator's code.

Inputs: time_period.

cancel_all_ordersA
Destructive
Inspect

KILL SWITCH — cancel every resting Polymarket order on the operator account at once. Use when exposure must go to zero fast. Respects dry-run.

Inputs: no named parameters.

cancel_orderB
Destructive
Inspect

Cancel an open order by id (respects dry-run).

Inputs: order_id (required).

check_orderA
Read-onlyIdempotent
Inspect

CHECK BEFORE YOU PLACE: deterministic verification of a proposed order against the operator's intent, the live market and the guardrails. Pass the operator's own words as intent. Returns ok / caution / block with the evidence per check (market exists and is open, intent matches the market and the YES/NO side, price is sane vs the book, size and $1 minimum, guardrails, liquidity, resolution source) plus a one-line read-back. No model judges anything; nothing is sent.

Inputs: side (required), size (required), price (required), venue (required), +3 more.

closing_soonA
Read-onlyIdempotent
Inspect

Markets closing within N hours on either venue, by volume — where trading activity concentrates.

Inputs: hours, limit, venues.

compare_venuesA
Read-onlyIdempotent
Inspect

Find markets that may be the SAME event on both Polymarket and Kalshi. NOT an arbitrage scanner: matches are candidates from title similarity plus a close-date check, and a price difference between two candidates is not profit. Identical wording does not mean identical resolution criteria — read both, and run quote_cost on each leg, before acting.

Inputs: query (required), limit, min_similarity, max_close_days_apart.

dispute_riskA
Read-onlyIdempotent
Inspect

PREMIUM SIGNAL — dispute-risk triage. Scores 0-100 how likely a market's resolution gets contested (UMA dispute risk) with transparent reasons. Takes the market slug, the Gamma id, or a CLOB token id (the market_id a search returns).

Inputs: id_or_slug (required).

find_marketsA
Read-onlyIdempotent
Inspect

Search BOTH Polymarket and Kalshi at once and return one normalised shape per market: venue, market_id (the id that venue's place_order takes), title, yes/no price as probabilities in (0,1), best bid/ask, spread, 24h volume, close time. Use this instead of the per-venue search tools when you do not already know the venue.

Inputs: query (required), limit, venues.

get_marketA
Read-onlyIdempotent
Inspect

Get one market's details. Accepts the market slug, the Gamma market id, or either of its CLOB token ids (the market_id that find_markets and search_markets return), so a token id from a search can be passed straight in.

Inputs: id_or_slug (required).

get_orderbookB
Read-onlyIdempotent
Inspect

Get the live orderbook (bids/asks) for a CLOB token id.

Inputs: token_id (required).

get_positionsC
Read-onlyIdempotent
Inspect

Current positions for a wallet address.

Inputs: address (required), limit.

kalshi_balanceA
Read-onlyIdempotent
Inspect

Kalshi account balance (needs the operator's API key).

Inputs: no named parameters.

kalshi_cancel_orderA
Destructive
Inspect

Cancel a Kalshi order by id (respects dry-run).

Inputs: order_id (required).

kalshi_get_marketB
Read-onlyIdempotent
Inspect

Get one Kalshi market by ticker.

Inputs: ticker (required).

kalshi_get_orderbookA
Read-onlyIdempotent
Inspect

Kalshi orderbook for a ticker, normalised to a YES-book bid/ask view (Kalshi publishes bid ladders only; asks are derived as 1 - NO bid). Raw ladders included.

Inputs: ticker (required), depth.

kalshi_get_tradesB
Read-onlyIdempotent
Inspect

Recent public trades for a Kalshi ticker.

Inputs: ticker (required), limit.

kalshi_open_ordersD
Read-onlyIdempotent
Inspect

Kalshi resting orders (needs the operator's API key).

Inputs: limit.

kalshi_place_orderB
Destructive
Inspect

Place a Kalshi limit order. State it naturally: outcome yes|no, action buy|sell, price = probability of THAT outcome in (0,1). Translated to Kalshi's YES-book bid/ask internally. DRY-RUN by default.

Inputs: count (required), price (required), action (required), ticker (required), +2 more.

kalshi_positionsD
Read-onlyIdempotent
Inspect

Kalshi positions (needs the operator's API key).

Inputs: limit.

kalshi_search_marketsA
Read-onlyIdempotent
Inspect

Search Kalshi markets. Kalshi has no text-search endpoint, so this pages open markets and filters on title/ticker; auto-generated MVE combo shards are excluded. Prices are dollar strings, not cents.

Inputs: limit, query, min_volume.

merge_positionsA
Destructive
Inspect

Merge matching YES+NO shares back into USDC, GASLESS via the relayer. amount is in shares, or 'max' for the largest balanced amount held. Needs the operator's relayer key. DRY-RUN by default.

Inputs: condition_id (required), amount.

my_balanceA
Read-onlyIdempotent
Inspect

Authenticated Polymarket cash and allowance snapshot for an existing configured wallet. Cash is separate from positions value; available-to-trade remains unknown until outstanding orders and unsettled fills are reconciled. Requires local account credentials. In simulation use paper_positions.

Inputs: no named parameters.

my_fillsB
Read-onlyIdempotent
Inspect

Recent executions (fills) for the operator wallet — confirms what actually traded, with tx hashes.

Inputs: limit.

my_positionsA
Read-onlyIdempotent
Inspect

The operator's current Polymarket positions (uses the configured wallet; no address needed).

Inputs: limit.

open_ordersA
Read-onlyIdempotent
Inspect

List the operator wallet's open orders.

Inputs: no named parameters.

order_statusA
Read-onlyIdempotent
Inspect

Status of one Polymarket order: resting, partially filled, filled, or gone. The lifecycle answer an agent needs after place_order.

Inputs: order_id (required).

overshoot_signalB
Read-onlyIdempotent
Inspect

PREMIUM SIGNAL — overshoot/fade detector. Analyzes a token's recent price series for fresh panic jumps and reports whether a fade setup is active plus this market's historical reversion tendency.

Inputs: token_id (required), hours, threshold, lookback_s.

paper_positionsA
Read-onlyIdempotent
Inspect

Paper-trading portfolio for dry-run: cash, positions at current marks, realized and unrealized P&L, resting paper orders (filled here if the market has crossed them). Dry-run Polymarket orders are papered against the live book automatically. Simulated: no queue, no impact, no fees, so results are an upper bound.

Inputs: no named parameters.

paper_resetA
Destructive
Inspect

Reset the paper-trading ledger to its starting bankroll (ODDSRAIL_PAPER_BANKROLL, default 1000 USDC). Deletes simulated fills and positions; touches nothing real.

Inputs: no named parameters.

place_orderA
Destructive
Inspect

Place a limit order. DRY-RUN by default: returns the order it would post. Real trading needs ODDSRAIL_DRY_RUN=0 and POLYMARKET_PRIVATE_KEY. The operator's builder code is signed into the order. price is the implied probability in (0,1); size is in SHARES (notional = price * size), and the exchange enforces a $1 minimum notional on marketable orders. post_only=True rejects rather than crosses the book.

Inputs: side (required), size (required), price (required), token_id (required), +1 more.

position_sizeA
Read-onlyIdempotent
Inspect

Fractional-Kelly position size for a binary contract, given your bankroll, the market price, and YOUR fair value estimate. Caps at a fraction of full Kelly and refuses negative-edge bets. Returns its assumptions — subtract quote_cost before trusting the number.

Inputs: price (required), fair_value (required), bankroll_usd (required), max_fraction_of_kelly.

price_historyB
Read-onlyIdempotent
Inspect

Recent price history for a CLOB token id: hours back, at fidelity_minutes resolution.

Inputs: token_id (required), hours, fidelity_minutes.

quote_costA
Read-onlyIdempotent
Inspect

What a given size would ACTUALLY cost, by walking the order book rather than reading the top level. Returns average fill price, slippage vs best, notional, and the levels consumed — plus the venue's fee schedule where it publishes one. Call this before sizing any trade, and on both legs before acting on a cross-venue gap.

Inputs: side (required), size (required), venue (required), market_id (required).

redeemable_positionsA
Read-onlyIdempotent
Inspect

What the operator can turn back into USDC now: redeemable (resolved, winning) positions and mergeable (hold both YES and NO) positions, with the ids the gasless tools take. Uses the configured wallet.

Inputs: limit.

redeem_positionsA
Destructive
Inspect

Redeem the winning shares of a RESOLVED market for USDC, GASLESS via the relayer. Pass exactly one of condition_id or market_id. Needs the operator's relayer key. DRY-RUN by default.

Inputs: market_id, condition_id.

resolution_criteriaA
Read-onlyIdempotent
Inspect

READ BEFORE TRUSTING A PRICE: the full resolution contract for a market — what exactly resolves YES, who resolves it, from which sources. venue is 'polymarket' (pass the slug, the Gamma id, or the market_id a search returned, which is a CLOB token id) or 'kalshi' (pass the ticker).

Inputs: venue (required), market_id (required).

search_marketsA
Read-onlyIdempotent
Inspect

Search Polymarket markets by text (Gamma public-search under the hood); empty query lists open markets. Returns token ids, prices, metrics, resolution info.

Inputs: limit, query.

server_infoA
Read-onlyIdempotent
Inspect

Server status: dry-run state, attribution config, enabled capabilities, venue reachability from this machine, and Polymarket's geoblock verdict for this machine's IP (advisory — not a compliance check). Call this before the first order of a session.

Inputs: no named parameters.

settlement_auditA
Read-onlyIdempotent
Inspect

Settlement-divergence audit for a cross-venue pair, on LIVE data (no pre-curated pair list). Compares close times, resolution sources, UMA dispute status and market structure, and returns ok / caution / block with reasons. polymarket_id takes the slug, the Gamma id or the market_id a search returned (a CLOB token id); kalshi_ticker takes the ticker. Run this before treating any cross-venue price difference as an edge.

Inputs: kalshi_ticker (required), polymarket_id (required), notional_usd.

split_positionA
Destructive
Inspect

Split USDC collateral into a full YES+NO share set for one market, GASLESS via Polymarket's relayer. amount_usdc is collateral in USDC (e.g. 25). Needs POLYMARKET_RELAYER_API_KEY and POLYMARKET_RELAYER_API_KEY_ADDRESS (polymarket.com -> Settings -> Relayer API keys). DRY-RUN by default. Never falls back to a gas-paying broadcast.

Inputs: amount_usdc (required), condition_id (required).

watch_bookA
Read-onlyIdempotent
Inspect

Stream one Polymarket token's realtime market events (book snapshot, price changes, trades) for up to seconds (1-60) or max_events, then return them. Use after get_orderbook when you need to see the book MOVE before acting; a quiet market may deliver only the initial snapshot.

Inputs: token_id (required), seconds, max_events.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.1/5.0

    Scored across 42 tools

    Disambiguation4/5

    The venue prefixes (kalshi_ vs no prefix) and action nouns keep most tools distinct. Only mild overlaps exist—notably find_markets vs search_markets vs kalshi_search_markets, and my_positions vs get_positions—but the descriptions clarify when to use each. No tools are truly indistinguishable.

    Naming Consistency4/5

    Names are consistently lowercase snake_case and mostly follow a predictable venue_action_noun pattern, e.g. kalshi_place_order, get_orderbook, cancel_all_orders. A few noun-style names like server_info, builder_stats, and position_size break the verb-first feel, but there is no chaotic style mixing.

    Tool Count2/5

    42 tools is well beyond the 25+ threshold for 'too many' and feels heavy even for a two-venue trading platform. Many tools could be consolidated or grouped, such as search variants, position variants, and several signal/analysis utilities. The breadth is real, but the count creates selection overhead.

    Completeness4/5

    The toolkit is broad: market discovery, order placement/cancellation, balances/positions, paper trading, redemption, resolution checks, builder attribution, and cross-venue settlement audits are all covered. Minor gaps include Kalshi-specific order status/fill history and a dedicated Polymarket trade history tool, so agents may need to work around those edges.

    Maintenance

    ActivitySlowing
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Real-time prediction market intelligence for AI agents. Query Polymarket and Kalshi markets, wallet profiles, smart money leaderboards, social pulse signals, price candlesticks, and orderbook data — 13 agents, one MCP connection. Powered by 1.1TB+ of historical data.
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Prediction market probability oracle for AI agents. 26 tools across 500+ live markets from Kalshi and Polymarket. Cross-source arbitrage detection, structured TPF signals, Kelly Criterion sizing, agent performance tracking, and webhook alerts.
      9
      250 npm
      1
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      An MCP server and Python toolkit that provides AI agents with real-time tools for Polymarket prediction markets, including liquidity scanning, arbitrage detection, and slippage estimation. It also offers advanced wallet intelligence, portfolio risk calculation, and probabilistic reasoning to enhance market analysis and strategy.
      71 PyPI
      1
      MIT
    • A
      license
      A
      quality
      C
      maintenance
      Enables AI agents to discover and analyze prediction markets, execute trades, and manage positions on Polymarket via the Model Context Protocol.
      7
      169 npm
      22
      MIT