Skip to main content
Glama
multi-exchange-spread

multi-exchange-spread

by tordagaz-ops
README.md
# multi-exchange-spread

**The same coin on seven exchanges, ranked by what the gap is actually worth
after both fees — with the order books walked, so the number you get is a number
you could have traded.**

Every exchange quotes BTC/USDT. They do not quote it at the same price. Between
them sits a spread you can cross: buy where it is cheap, sell where it is dear,
and if the gap is wider than two taker fees you keep the difference. The catch is
that the gap you see in a ticker is not the gap you get in a book — a ticker is a
single price with no size behind it, and by the time you have added up seven
venues, two symbols spellings and a fee schedule, the gap has usually closed.

This server answers the question directly:

- **Which pair of venues pays me right now?** One call, seven venues.
- **Is that gap real, or is one venue's quote stale?** Every spread above 200 bps
  is flagged `suspect`, and `estimate_trade` is the arbiter: it walks the real
  books level by level and charges both fees.
- **How big can I go?** `max_profitable_notional_usd` is the largest size whose
  round trip still clears the fees on the liquidity that actually rests there.
- **What about the rest of the market?** One scan ranks 60 pairs by net spread —
  2,400+ on demand.

```text
get_spread("BTC/USDT")                       → 7 venues + the best pair
scan_spreads(limit=10, min_turnover_24h=1e6) → the market, ranked by net bps
estimate_trade("BTC/USDT", notional_usd=10000) → books walked, fees charged
list_venues(probe=True)                      → who is answering, and how fast
```

- **No API key.** Every endpoint here is public. Nothing to register, nothing to
  leak.
- **Exchanges are a parameter, never a repository.** Seven venues, one server,
  one answer.
- **Fails soft.** A venue that is down is named in `unavailable` next to the data
  from the venues that answered. Partial results beat no results.
- **Honest by construction.** Fees are charged twice, per side. A trade that
  loses money says so, in dollars.
- **English, Spanish, Russian** — including the tool descriptions the model
  reads. Set `MCP_LOCALE`.

[Español](README.es.md) · [Русский](README.ru.md)

---

## The one piece of arithmetic that matters

Prices are quoted in the quote currency per unit of the base currency. A trade
costs a fee on **each** leg, so a round trip costs `2 × fee_bps`. That single
fact decides everything:

| Step | Formula | Example |
| --- | --- | --- |
| Gross spread | `(sell_bid − buy_ask) / buy_ask × 10000` | 60,700.70 → 60,715.30 = **2.405 bps** |
| Round-trip fee | `2 × fee_bps` | 10 bps each way = **20 bps** |
| Net spread | `gross − round trip` | 2.405 − 20 = **−17.595 bps** |
| Profit on size | `net_bps / 10000 × notional` | −17.595 bps on 10,000 USD = **−17.60 USD** |

On a pair of deep, liquid books the honest answer is usually negative: BTC/USDT
across seven exchanges typically sits inside one or two basis points, and two
taker fees are twenty. That is not the tool being pessimistic. That is why
cross-exchange arbitrage is a professional business with fee tiers and maker
rebates, and it is the single most useful thing this server can tell you before
you wire money to an exchange.

The interesting rows are elsewhere — thinner pairs, newer listings, venues whose
quote has not caught up yet.

## What the numbers mean

| Field | Meaning |
| --- | --- |
| `gross_bps` | The gap before fees, in basis points of the buy price. |
| `fee_bps_round_trip` | `2 × fee_bps`. The bar a spread must clear to be worth anything. |
| `net_bps` | `gross_bps − fee_bps_round_trip`. The only number that pays. |
| `capacity_usd` | How much the thinner side of the two touches can absorb. |
| `profit_usd_at_capacity` | Net profit if you traded exactly that. |
| `suspect` | `true` when `gross_bps > 200`. Almost always a stale ticker or a different token, not free money. |
| `buy_size` / `sell_size` | Base units resting at the touch. `null` when a venue publishes no sizes (Gate). |

`suspect` is a warning, not a verdict. A real spread of 764 bps does exist on the
day a token lists on a second venue, and a stale quote looks exactly the same
from the top of the book. The way to tell them apart is `estimate_trade`: it
reads the depth, so a phantom spread usually collapses to nothing the moment the
books are consulted.

## Tick tock: why a ticker is only a candidate

Order books refresh in milliseconds; tickers are aggregates refreshed every few
seconds. Measured on volatile pairs, a ticker routinely lags its own book by 10
to 60 bps. That is enough to invent a spread that does not exist.

So the design is two-stage. Tickers are a **candidate generator** — they tell you
where to look. `estimate_trade` is the **arbiter** — it fetches both books and
answers with prices you could have hit, sizes that actually rested there, and
fees charged on both legs. When a candidate is flagged `suspect`, do not act on
`get_spread`; call `estimate_trade` and let the books decide.

---

## Install

```bash
pip install mcp-multi-exchange-spread
```

Or from this repository:

```bash
git clone https://github.com/tordagaz-ops/multi-exchange-spread
cd multi-exchange-spread
python -m venv .venv
.venv\Scripts\activate          # Windows
source .venv/bin/activate       # macOS / Linux
pip install -e ".[dev]"
```

Python 3.10+. The only dependencies are `mcp` and `httpx`.

## Run

```bash
python -m mcp_spread_scanner                      # stdio, for a desktop client
MCP_TRANSPORT=http python -m mcp_spread_scanner    # http on port 8000
MCP_TRANSPORT=sse  python -m mcp_spread_scanner    # sse on port 8000
```

A client configuration:

```json
{
  "mcpServers": {
    "multi-exchange-spread": {
      "command": "python",
      "args": ["-m", "mcp_spread_scanner"],
      "env": { "MCP_LOCALE": "en" }
    }
  }
}
```

## Docker

```bash
docker build -t multi-exchange-spread .
docker run --rm -i multi-exchange-spread
```

See [`Dockerfile`](Dockerfile) — stdio transport, no ports, no volumes.

---

## The four tools

### `get_spread` — one pair, every venue

| Parameter | Type | Default | Notes |
| --- | --- | --- | --- |
| `symbol` | string | — | `BTC/USDT`, `BTCUSDT`, `btc-usdt` all work. |
| `venues` | list or string | all seven | `["bybit","okx"]` or `"bybit, okx"`. |
| `fee_bps` | number | `10` | Per-leg taker fee. Your fee tier changes the answer. |

Real output, BTC/USDT, one afternoon, seven venues answering:

```json
{
  "symbol": "BTC/USDT",
  "fee_bps": 10.0,
  "fee_bps_round_trip": 20.0,
  "quoted": 7,
  "best": {
    "buy_venue": "mexc",  "buy_price": 60700.70, "buy_size": 0.0115,
    "sell_venue": "gate", "sell_price": 60715.30, "sell_size": null,
    "gross_bps": 2.405,
    "fee_bps_round_trip": 20.0,
    "net_bps": -17.595,
    "capacity_usd": 473.20,
    "profit_usd_at_capacity": -0.83,
    "suspect": false
  },
  "warnings": [],
  "fee_note": "Fees are per side and are charged twice per round trip: 10 bps each way means a spread must exceed 20 bps to be worth anything."
}
```

`venues` carries every quote with its mid, its own spread in bps, the size at the
touch, 24-hour turnover and a timestamp, so you can see the market the way the
server saw it rather than trusting one summary line.

### `scan_spreads` — the whole market, ranked

| Parameter | Type | Default | Notes |
| --- | --- | --- | --- |
| `venues` | list or string | all seven | Restrict the field. |
| `symbols` | list or string | auto | Pin the pairs instead of scanning. |
| `fee_bps` | number | `10` | Per-leg fee. |
| `min_net_bps` | number | `0` | Drop rows below the bar. |
| `min_turnover_24h` | number | `1000000` | Skip pairs nobody trades. |
| `limit` | integer | `10` | Rows returned, 1–50. |
| `shortlist` | integer | `60` | Pairs examined after ranking, 2–200. |
| `sort` | string | `net_bps` | or `gross_bps`, or `turnover`. |

Measured run with defaults: **60 pairs scanned, 52 with a two-venue pair, 5 rows
above the turnover floor** — the rest were inside the fee.

```text
INIT/USDT    gross= 764.27  net= 744.27  buy=kucoin  sell=binance  suspect=true
MANTRA/USDT  gross= 204.00  net= 184.00  buy=binance sell=mexc     suspect=true
MTX/USDT     gross=  95.67  net=  75.67  buy=kucoin  sell=bitget   suspect=false
EVAA/USDT    gross=  30.43  net=  10.43  buy=mexc    sell=kucoin   suspect=false
TAO/USDT     gross=  25.60  net=   5.60  buy=mexc    sell=kucoin   suspect=false
```

The scan is two-phase on purpose. Phase one asks every venue for its whole market
— one request each, 460 to 3,614 pairs — ranks by 24-hour turnover and keeps the
shortlist. Phase two fetches quotes only for the shortlist. That is why a scan of
the entire spot market costs about a second instead of a thousand requests.

### `estimate_trade` — the books, not the tickers

| Parameter | Type | Default | Notes |
| --- | --- | --- | --- |
| `symbol` | string | — | The pair to size. |
| `notional_usd` | number | `10000` | Dollars to put through, 10–5,000,000. |
| `buy_venue` | string | auto | Force the buy leg. |
| `sell_venue` | string | auto | Force the sell leg. |
| `venues` | list or string | all seven | Restrict the candidate books. |
| `fee_bps` | number | `10` | Per-leg fee charged on both legs. |

It fetches up to 50 levels per venue, walks both ladders to fill the requested
size, and returns the arithmetic on what was actually available:

```json
{
  "symbol": "BTC/USDT",
  "notional_usd": 10000.0,
  "buy_venue": "mexc", "sell_venue": "bitget",
  "buy":  { "spent_usd": 10000.0, "quantity": 0.16475801, "vwap": 60695.08, "levels_used": 2, "complete": true },
  "sell": { "spent_usd": 10000.0, "quantity": 0.16474269, "vwap": 60700.72, "levels_used": 1, "complete": true },
  "gross_bps": 0.93,
  "gross_pnl_usd": 0.93,
  "fees_usd": 20.00,
  "net_pnl_usd": -19.07,
  "net_bps": -19.07,
  "profitable": false,
  "chosen_by": "best_net",
  "books_compared": 42,
  "max_profitable_notional_usd": 0.0,
  "warnings": ["After both fees this trade loses 19.0693 USD on 10000 USD traded."]
}
```

Three honest details in that answer:

1. `books_compared: 42` — every cross-venue combination of the seven books was
   priced, not just the pair the tickers liked. `chosen_by` says whether the tool
   picked the best one (`best_net`) or you forced it (`requested`).
2. `max_profitable_notional_usd: 0.0` — on this pair, at this fee, no size wins.
   The search stops at the liquidity that exists; a size the books cannot fill is
   reported as `complete: false`, never as a profit.
3. `fees_usd` is charged on both legs at the prices actually paid, not on the
   requested notional.

### `list_venues` — who is answering

| Parameter | Type | Default | Notes |
| --- | --- | --- | --- |
| `probe` | boolean | `true` | Fetch BTC/USDT from each venue and time it. |

```text
bybit    whole_market=true   ok=true  latency=1051 ms  pairs=460
binance  whole_market=true   ok=true  latency=1388 ms  pairs=2472
okx      whole_market=true   ok=true  latency=351 ms   pairs=495
bitget   whole_market=true   ok=true  latency=428 ms   pairs=3614
kucoin   whole_market=true   ok=true  latency=377 ms   pairs=805
mexc     whole_market=true   ok=true  latency=121 ms   pairs=1574
gate     whole_market=false  ok=true  latency=261 ms   pairs=null
```

With `probe=false` no venue is contacted at all: the tool then answers purely
from the built-in catalogue, which is what you want when you are debugging your
own client and do not want to wait on seven networks.

## The venues

| Venue | Whole-market scan | Symbol spelling | Notes |
| --- | --- | --- | --- |
| Bybit | yes | `BTCUSDT` | Public spot tickers and 50-level books. |
| Binance | yes | `BTCUSDT` | Leveraged tokens (`BTCUP`, `BTCDOWN`) filtered out. |
| OKX | yes | `BTC-USDT` | USDT pairs only. |
| Bitget | yes | `BTCUSDT` | Deepest listing count of the seven. |
| KuCoin | yes | `BTC-USDT` | `level2_100` books, USDT only. |
| MEXC | yes | `BTCUSDT` | Book ticker plus a separate 24h turnover pass. |
| Gate | no | `BTC_USDT` | No sizes in its ticker; the book supplies them. Queried per pair. |

Gate is the exception to the whole-market scan, and the reason is measurable: its
market-wide ticker endpoint does not serve spot pairs the way the other six do.
Rather than pretend, this server marks it `whole_market=false`, gives it the
shortlist from the other venues and asks it pair by pair. That is also why a
Gate quote can arrive with `bid_size: null` — no sizes in the ticker, and the
scan does not pay for a book per pair.

## Errors

Failure is a payload, never an exception, and never a crash:

| Code | Meaning | What to do |
| --- | --- | --- |
| `empty_symbol` | Nothing was given, or every item was junk. | Supply a pair like `BTC/USDT`. |
| `invalid_symbol` | No quote currency could be read. | `BTC`, `$`, `%%` are not pairs. |
| `unknown_symbol` | No venue listed that pair. | Check the spelling; try the base alone. |
| `unknown_venue` | A name is not in the catalogue. | `list_venues` names them. |
| `too_few_venues` | Fewer than two venues answered. | Nothing to pair; retry or widen `venues`. |
| `no_pair` | Quotes exist but no usable bid/ask pair. | Usually one-sided or zero-size quotes. |
| `no_book` | Depth unavailable for that pair. | Some venues do not publish every book. |
| `no_data` | Every venue failed. | Network or a venue-wide outage. |
| `invalid_number` / `invalid_limit` / `invalid_sort` | A parameter is out of range or not a number. | The message carries the bounds. |
| `timeout` / `network_error` / `upstream_unavailable` / `upstream_rejected` / `bad_payload` | A venue misbehaved. | Shown per venue in `unavailable`. |

Every one of those messages is translated, and every payload is a plain dict you
can log, diff and replay.

## Tests

**204 tests, four layers**, all in this repository:

| Layer | Count | What it proves |
| --- | --- | --- |
| Unit | 166 | The arithmetic, the adapters against recorded payloads, the words, every input rejection, and all four tools in-process. |
| End-to-end | 17 | The real process over stdin/stdout: handshake, published schema, translations, every rejection path that must not touch a network. |
| Live | 21 | The seven real venues, right now: quotes, books, a full scan, a sized trade. |
| Docker | — | Build, then a handshake and a `tools/list` inside the container. |

```bash
pytest                 # offline: unit + end-to-end
pytest -m live         # the real venues
pytest -m "not live"   # fast, deterministic, no network
```

The adapter tests do not invent JSON. `tests/fixtures/venues.json` is a recording
of the seven exchanges, captured by `_record.py` and trimmed to the pairs the
tests use, so a venue changing a field name shows up as a failing test instead of
a silent `null` in production. `_record.py` is included: when a venue moves, run
it, watch the diff, fix the adapter, and the recording is your evidence.

## Design notes

**Why not one server per exchange?** Because the product is the comparison. A
Bybit-only server cannot tell you that OKX is paying more; it can only tell you
about Bybit. Venues are a parameter, and the answer is a pair of legs.

**Why a shortlist instead of a full fan-out?** Asking seven venues about 400
pairs each is 2,800 requests. Ranking by turnover and fetching 60 pairs costs
about 150 and finds the same opportunities, because a spread on a pair with
10,000 USD of daily volume is not a trade anyone can do at size.

**Why time out at 3.5 seconds per venue?** A slow venue must not hold the answer
hostage. When the gather deadline passes, whatever arrived is returned and the
rest is named in `unavailable`. Six seconds is the outer budget for the whole
call.

**Why cache at all?** Sixty seconds for market-wide tickers and five for a book,
so a model asking the same question twice in a row costs one request, not two.
Every quote carries `fetched_at`, so the answer is never older than it claims.

## Locales

`MCP_LOCALE=en|es|ru` selects the language of the instructions, the four tool
descriptions, every parameter description and every error message. English is the
default; an unknown value falls back to English rather than failing. The payload
keys never change, so a client can log in one language and display in another.

## Licence

MIT. The data belongs to the exchanges; the arithmetic is ours. Nothing here is
investment advice, and a spread that survives both fees is still a trade with
execution risk on two venues at once.

TDQS

A4/5.0

Scored across 4 tools

Disambiguation5/5

Each tool occupies a distinct scope: get_spread is a single-pair snapshot, scan_spreads is a ranked cross-pair list, estimate_trade is a fill/execution simulation, and list_venues is venue metadata/health. The descriptions even state the division of labor ('this is the tool that decides whether a scan row is real', 'call it first when a scan looks empty'), leaving little room for misselection.

Naming Consistency5/5

All four names follow a uniform snake_case verb_noun pattern (get_, scan_, estimate_, list_) and read predictably. No mixed conventions or vague bare verbs.

Tool Count5/5

Four tools is a tight, well-scoped set for a spread-analytics server, and each one covers a distinct stage (discover venues, find candidates, inspect a pair, validate a trade). Nothing looks redundant or tacked on.

Completeness4/5

The surface covers the natural workflow end to end: venue discovery/health, spread scanning, per-pair detail, and feasibility estimation. Minor gaps exist, such as no historical/time-series spread queries or venue-scoped filtering, but agents can work around these.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues