Skip to main content
Glama
linedrift-mcp

linedrift-mcp

by jman563412
README.md
# linedrift

Compares sports lines across **Kalshi, Pinnacle, SX Bet and Polymarket**. It matches the same game on each venue
(team-name aliasing, school-name disambiguation), removes the vig from the sportsbook lines, and scores Kalshi's
fee-adjusted prices against each reference. It comes as a CLI and an **MCP server**, so an AI agent can run scans and
compare lines in plain language. It also includes an evaluation harness that records every comparison and checks it
against settled results. That harness is what showed there's no reliable edge (see [Results](#results)).

**Nothing here places a bet without you.** Line comparison uses only public read endpoints and needs no account or
database. Live orders (see below) need Kalshi credentials in `.env`, go through a `y/N` prompt, and are off entirely in
the MCP server unless it is started with `LINEDRIFT_LIVE=1`. It was built as a paper-evaluation harness for a small
account; the spec is explicit that at that size the ceiling is cents per week, and that the deliverable is the evidence
to decide whether funding the account further is justified — not a profit engine.

## Install and run

Python 3.11+. Dependencies are `requests` and, for tests, `pytest`.

```
uv sync --extra dev
cp .env.example .env                        # every key is optional for line comparison
uv run pytest
uv run linedrift scan --league NCAAF        # compare lines; writes nothing unless recording is on
uv run linedrift settle                     # recording only: resolve paper positions
uv run linedrift report                     # recording only: calibration and paper P&L
uv run linedrift harvest --leagues NCAAF NFL
```

**References:** SX Bet and Polymarket are keyless. Pinnacle comes through the PinnAPI reseller (`PINNAPI_KEY`; the
free tier works). Its latest pull per league is cached for 10 minutes as JSON under `.cache/pinnacle/`
(`LINEDRIFT_CACHE_DIR` to move it), and `PINNACLE_DAILY_BUDGET` (default 80) caps requests per UTC day.

### `linedrift scan`

Reads both venues, maps SX markets onto Kalshi markets, runs the detectors,
and prints ranked candidates. Nothing is ranked or displayed on gross edge.

```
ticker                          market    src buy    ref    ask  net(take)  net(make)  conf  action
---------------------------------------------------------------------------------------------------
KXNFLGAME-26SEP27KCMIA-KC                 pin no    0.84   0.87      1.46c      3.11c  1.00  rest_maker
KXNFLSPREAD-26SEP27HOUIND-HOU3  HOU -2.5  pin no    0.52   0.55      0.55c      2.85c  1.00  rest_maker
KXNFLTOTAL-26SEP27MINTB-47      O 46.5    sx  yes   0.41   0.42     -2.40c      2.89c  1.00  rest_maker
```

| column | meaning |
|---|---|
| `ticker` | Kalshi market ticker. A structural row joins every leg of the position with commas. |
| `market` | the line, for spread and total markets: `HOU -2.5` (HOU lays 2.5), `O 46.5` (over). Blank for a winner market. |
| `src` | which reference the row was scored against: `sx` (SX mid) or `pin` (de-vigged Pinnacle line) |
| `buy` | the contract to buy: `yes` or `no`. Every market is scored in both directions from the one reference; `no` on a spread is the dog covering, `no` on a total is the under. |
| `ref` | reference probability **of YES** the edge is measured against: SX mid or Pinnacle's, for divergence; `1.00` for structural, the $1 that exactly one leg pays out |
| `ask` | Kalshi best YES ask (always YES-scale, whichever side `buy` names); for structural, the sum of the legs' asks (the cost of buying every leg) |
| `net(take)` | per-contract edge in cents **after** the Kalshi taker fee, crossing the spread on the `buy` side |
| `net(make)` | per-contract edge in cents **after** the Kalshi maker fee, resting on the `buy` side (a resting NO bid is a resting YES ask) |
| `conf` | mapping confidence, 0–1 (`1.00` for structural, which carries no mapping risk) |
| `action` | `take` (net taker edge ≥ 2c and fillable at the touch), `rest_maker` (net maker edge ≥ 0.5c), or `skip` (never printed) |

A market with a usable reference from both venues produces two rows —
`divergence` (`sx`) and `pinnacle_divergence` (`pin`) — scored and recorded
independently, so the paper record can tell which reference is actually
better calibrated. Flags: `--league {NBA,NCAAF,NFL,UFC}`, `--max-events N`
(Kalshi events to fetch orderbooks for, nearest kickoff first),
`--max-sx-markets N` (SX winner markets to consider, in API order),
`--market-types {winner,spread,total}...` (which Kalshi series to read;
default all the league offers), `--max-line-markets N` (spread/total
markets to score per reference, nearest kickoff first; default 500 covers
a full NCAAF slate), `--no-pinnacle` (skip the Pinnacle pass
entirely), `--seed-path FILE` (alias table; see harvest).

Spreads and totals never go through the name matcher. A line market is
joined to a game the winner matcher already accepted — same Kalshi game
code, same team code, same line on the reference venue — so a Kalshi strike
the reference does not offer is simply not scored, and a game whose two
winner legs point at different reference events is dropped outright.

### `linedrift harvest`

Sweeps a full slate, matches SX team names onto Kalshi's, then does the same
against Pinnacle's (a second pass — Pinnacle's team naming doesn't overlap
with SX's, so its aliases have to be learned separately). Writes any alias
that changed a matching outcome into `seed_aliases.json` (merged, atomic,
both passes sharing the one file), and prints the names it could not resolve
for one sitting of human review. Rows a human writes back into that file are
read by `scan` on every run.

### Paper trading (optional): `scan` records, `settle` resolves, `report` evaluates

Recording is **off by default**, and no database is created. Set `LINEDRIFT_RECORD=1` in `.env` to turn it on, or
pass `--record` / `--no-record` (MCP: `record=`) to override it for one scan. `settle` and `report` work on an existing
record and otherwise say how to start one.

With recording on, every `scan` writes what it scored to `linedrift.db` (SQLite, WAL; `--db` or
`LINEDRIFT_DB` to move it): one row per scored market
including `skip`s, because a usable SX reference is a calibration observation
whether or not Kalshi was mispriced. Each actionable signal opens two paper
positions of one contract — a taker at the ask and a maker at the bid, so the
two fill models are compared on the same markets — unless already open.

`linedrift settle` asks Kalshi for each open position's result. Taker
positions settle on the result less the taker fee. Maker positions count as
filled only if the market **traded strictly through** the resting bid before
kickoff on real volume (one-minute candlesticks); otherwise they close as
`unfilled` with zero P&L. Even so, maker figures are optimistic — resting
orders fill disproportionately when the other side knows something — and the
report labels them that way. A structural position settles when exactly one
leg pays; anything else is `void`.

`linedrift report` prints, per detector and fill model: settled count, net
P&L, then the **Brier score** of the reference probability against outcomes
and a said-vs-happened table in 20-point buckets. Calibration is the headline;
at these sample sizes P&L is variance.

### MCP server

The same functions as MCP tools, for AI clients. Read-only unless started
with `LINEDRIFT_LIVE=1`, which adds `place_order`, `cancel_order`,
`list_orders` and `balance`.

```
claude mcp add --scope user linedrift -- uv run --directory /path/to/linedrift linedrift-mcp
```

| tool | does |
|---|---|
| `list_leagues()` | the four league codes |
| `scan_kalshi(league, max_events=50, max_sx_markets=50, record=True, pinnacle=True)` | scan; returns signals as JSON (decimals as strings, cents to 2dp) plus the `pending` / `mapped` / `usable_references` counts and their Pinnacle equivalents (`pinnacle_references`, `pinnacle_note`), and records unless told not to |
| `settle_paper()` | `linedrift settle` |
| `paper_report()` | `linedrift report` |

## Results

From recording every scan between September 13 and November 23, 2026 (NFL, college football, NBA and UFC), using `linedrift report`:

| reference | games | Brier (0.25 = coin flip) | taker: avg per position (95% range, by game) | maker (optimistic): avg per position (95% range) |
|---|---|---|---|---|
| SX Bet | 445 | 0.227 | −2.65c (−5.08c to −0.22c) | −2.81c (−7.63c to +2.00c) |
| Pinnacle | 333 | 0.236 | −2.03c (−4.77c to +0.72c) | −0.19c (−5.30c to +4.91c) |
| Polymarket | 119 | 0.196 | −3.07c (−6.25c to +0.10c) | −2.13c (−10.95c to +6.68c) |

- **The references are well calibrated:** when a reference said ~50%, it happened ~49–50% of the time, and the other
  buckets track similarly. The Brier scores aren't directly comparable across rows, because each reference covers a
  different set of markets.
- **No reliable edge:** following SX's taker flags lost money, with the whole 95% range below zero. Every other row is
  negative on average.
- **A tiny edge may still exist:** for Pinnacle, Polymarket and every resting-bid (maker) row, the range includes
  zero. The sample is too small to rule a small edge out, and a larger sample would be needed to say either way. Maker
  figures are optimistic: fills are assumed on any print through the bid, and adverse selection isn't modelled.

## Fee model

The only fee schedule in the code, applied everywhere:

```
taker = ceil(M * 0.07   * C * P * (1 - P))   dollars, rounded UP to the cent
maker = ceil(M * 0.0175 * C * P * (1 - P))
```

At one contract and P = 0.50 the taker pays 2c and the maker 1c. Break-even
gross edge is therefore ~2c taking and ~1c making, which is why `rest_maker`
is the action a small account's economics favour.

## Current limitations

- **Two of the spec's three detectors run, plus a second reference for one of
  them.** Structural (Kalshi legs summing under 100c) and divergence (SX mid,
  and now also Pinnacle, vs Kalshi ask) both fire; movement/lag is not
  started. On liquid NCAAF books, two-leg sums have measured 100–102c against
  a 96c gate, so structural finds nothing there; divergence found its first
  live `rest_maker` on an NFL moneyline on 2026-09-13. `scan` prints how many
  markets mapped and how many had a usable reference, per venue, so "No
  candidates found." can be read.
- **Only outcome one of each SX or Pinnacle market is compared.** Both
  markets carry both teams; the mapper currently produces one reference per
  market (SX's `outcomeOneName`, Pinnacle's home side), so the Kalshi market
  for the other team is never scored by either divergence detector. Halving
  that gap is a mapping-layer change, shared by both.
- SX orderbook snapshots are read from `/orderbook-v3/snapshot`; the `/orders`
  endpoint in the design spec was retired by SX before this shipped.
- Alias auto-learning reports an honest zero on today's data. Harvest can only
  learn from pairs the matcher already accepted, and it only accepts pairs
  that already clear the threshold without an alias. Inference over the
  unresolved residual (two-leg elimination) is scheduled as its own task.
- Pre-game markets only: winner, spread and total. No in-game markets, and
  no alternate strikes the reference venue does not itself offer (Kalshi
  ladders every half point; SX and Pinnacle offer a handful of rungs, and
  only exact line matches are scored — nothing is interpolated).
- **Second reference source: Pinnacle, via the free PinnAPI reseller.**
  De-vigged with a **multiplicative (proportional) two-way** split — exactly
  invertible, `Decimal`-safe, no solver — chosen over power/Shin because at
  Pinnacle's normal ~2-4% overround the methods differ by well under the
  0.5c edge floor; a `[0.10, 0.90]` gate on the de-vigged probability (plus
  an overround gate of `[1.00, 1.08]` and a snapshot-age gate) rejects
  references at the extremes where that choice would start to matter, rather
  than trusting any single de-vig method out at the tails. Runs on **every**
  scan, not just where SX is thin: `pinnacle_divergence` is a separate
  detector from `divergence` so the paper record can compare them, meaning a
  market with both references produces two rows/observations, by design.
  Fetched per-sport (NFL+NCAAF share one call) through a SQLite-backed TTL
  cache (`PINNACLE_TTL_S`, default 600s) and a per-UTC-date request counter
  capped at `PINNACLE_DAILY_BUDGET` (default 80, headroom under the vendor's
  100/day) — the counter increments on attempt, not success, so a failing
  request still spends its slot. Exhausting the budget degrades that scan to
  SX-only with a printed note, exit 0, never a crash. Pinnacle's own
  per-event moneyline limit (`max_money_line`) is recorded on every
  observation but not yet gated on — the probed range didn't show it
  correlating with worse pricing. Needs `PINNAPI_KEY` in `.env`
  (free, no card); `PINNACLE_ENABLED=0` turns it off globally, `--no-pinnacle`
  turns it off for one scan.
- **Live execution is opt-in and hand-confirmed.** `linedrift place` sends a
  real order only after a `y` at the prompt (or `--confirm`); the MCP tools
  exist only when the server runs with `LINEDRIFT_LIVE=1`. Per-order caps
  default to 5 contracts / $2.00 and are set in `.env`.
- The calibration sample is small and grows only when scans are recorded. No
  holdout period has been reserved yet; do not make a funding decision on the
  report until one has.
- Orders placed straight through Kalshi's own UI (not via `place_order`)
  reach linedrift's local tracking passively: `preview()` (every `place`
  guardrail check) and `sync()` (every `settle`, and `orders`/`list_orders`
  by default) reconcile against `GET /portfolio/orders` first, backfilling
  anything not already in `live_orders` as `origin='manual'` before doing
  anything else -- so a bet placed in the Kalshi app shows up here, and trips
  the "already open on this ticker" guardrail, without ever running a
  separate command for it. Backfilled orders settle at the market result
  like any other, but stay excluded from every scanner statistic. `orders
  --reconcile` / `list_orders(reconcile=True)` still exist to reconcile on
  their own, without a sync alongside them.

## Live orders

Needs `.env` with `KALSHI_API_KEY` and `KALSHI_PRIVATE_KEY_PATH` (mode 600).

```
linedrift balance
linedrift place --signal 42                   # buy YES at the signal's price
linedrift place --ticker KXNFLGAME-... --buy --no --price 0.35 --rest --expires 2026-09-21T17:00:00Z
linedrift place --ticker KXNFLGAME-... --sell --yes --market --confirm
linedrift orders --sync                       # resting orders, refreshed -- also reconciles
linedrift orders --reconcile --all            # reconcile alone, without a sync
linedrift cancel <order id>
linedrift settle                              # paper AND live
linedrift report                              # gains a live section
```

`take` is immediate-or-cancel at your price; `rest` is post-only until
`--expires` or cancelled; `market` is immediate at the worst price. Orders
placed from a signal are tagged `signal`; everything else is `manual` and is
excluded from the scanner's statistics. Caps: `LINEDRIFT_MAX_COUNT`,
`LINEDRIFT_MAX_NOTIONAL_DOLLARS` in `.env`. Default size when you give neither
`--count` nor `--dollars`: `LINEDRIFT_ORDER_DOLLARS` worth (default $1).

**Without recording** there's no local order log, and Kalshi is the record. Placing by `--ticker`, `orders`,
`cancel` and `balance` work, and the one-open-order-per-market guard asks Kalshi for your resting orders. Placing by
`--signal`, live `settle`, `orders --sync/--reconcile` and the live report need `LINEDRIFT_RECORD=1`.

For MCP: `claude mcp add linedrift -e LINEDRIFT_LIVE=1 -- uv run --directory /path/to/linedrift linedrift-mcp`

## Layout

```
src/linedrift/
  fees.py            fee arithmetic (Decimal only, never float)
  types.py           Book, PriceLevel, MarketRef
  config.py          .env, credentials by name, order caps
  kalshi/            public read client; folds the two-ladder orderbook
                     auth.py (RSA-PSS signer), trade.py (signed V2 order client)
  sx/                public read client; normalizes SX markets
  pinnacle/          PinnAPI client, normalize, devig, TTL/budget cache
  mapping/           team-name canonicalization, alias table, matcher, harvest
  detect/            Signal, fee- and depth-aware scoring, the three detectors
  store.py           SQLite: signals, paper_positions, live_orders
  paper.py           record / settle / report (Brier, calibration, two fill models)
  execute.py         OrderIntent, LiveExecutor (preview/place/cancel/sync/settle), live report
  cli.py             `scan`, `settle`, `report`, `harvest`, `place`, `orders`, `cancel`, `balance`
  mcp_server.py      the same as MCP tools (`linedrift-mcp`)
tests/fixtures/      real API responses captured 2026-09-12
docs/superpowers/    design spec and the Phase 1 implementation plan
```