Skip to main content
Glama
Batch Slippage Bybit

Batch Slippage Bybit

by tordagaz-ops
README.md
# batch-slippage-bybit

**How much does this order actually cost, on this pair, at this size — and how
many child orders does Bybit make me place? One call answers both, for twelve
pairs and eight sizes at once.**

Sizing an order on a real exchange is not one question but five, and each one
hides inside the last:

1. **Where does the book run out?** A ticker is a single price with no size
   behind it. This server walks the actual levels, so a size that only fits in
   the top 0.01 BTC of the book reports the price it would really pay.
2. **Does the venue accept the quantity?** Bybit rounds every quantity *down* to
   1e-6 BTC on BTC/USDT, refuses anything worth less than 5 USDT, and caps a
   market order at 120 BTC — while the same pair accepts 230 BTC as a limit order.
3. **How much of that is fee, and how much is slippage?** They are different
   numbers and they are never mixed here: `slippage_bps` is the book, `fee_bps` is
   per side, `total_cost_bps` is the sum.
4. **How many orders do I have to split this into?** The ceiling is per order, so
   a 1 M USD buy cannot be one order. `plan_slices` returns the children, each
   capped at the ceiling, each priced against the depth the previous ones left.
5. **Can I ask that for a hundred pairs before I commit?** Yes — that is the
   whole point of a batch call.

```text
batch_slippage(["BTC/USDT","ETH/USDT"], [1_000, 10_000, 100_000])  → 6 rows, one call
plan_slices("BTC/USDT", target_usd=1_000_000, budget_bps=20)       → 5 child orders
check_order("BTC/USDT", quantity=200)                              → rejected: ceiling 120
list_instruments(search="BTC", min_turnover_24h=10_000_000)        → 18 liquid pairs of 466
list_venues(probe=True)                                            → latency and pair count
```

- **No API key.** Public market data only. Nothing to register, nothing to leak.
- **Read-only.** No tool places, cancels, signs or moves anything. Ever.
- **The venue is a parameter, not a repository.** Every tool takes `venue`; today
  there is one adapter (Bybit spot), and adding a second costs one class and one
  line, with no change to a single parameter or response field.
- **Fails soft.** A pair whose book times out is named in `unavailable` while the
  other pairs still answer, with a `partial_note` saying what is missing.
- **English, Spanish, Russian** — including the tool descriptions the model reads.
  Set `MCP_LOCALE`; English is the default.

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

---

## The one piece of arithmetic that matters

Prices are quote-per-base. Slippage is measured against the **mid**, and it is
always reported as a **cost** — positive is worse, whichever side you are on.
The fee is charged **per side**, so a round trip costs twice `fee_bps`.

| Step | Formula | Example (BTC/USDT, buy 100 000 USD) |
| --- | --- | --- |
| Mid | `(best_bid + best_ask) / 2` | 60 825.05 |
| Average price | `spent_usd / base_quantity`, walking the asks | 60 832.47 |
| Slippage | `(vwap − mid) / mid × 10 000` | **1.22 bps** |
| Fee, one side | `fee_bps` | **10 bps** |
| Total cost | `slippage + fee` | **11.22 bps** |
| Round trip | `slippage + 2 × fee` | 21.22 bps |

That last row is why a 0.008 bps "spread" is not a trade. On BTC/USDT the touch
costs **0.008 bps** of slippage and 10 bps of fee, and the fee is the entire
question.

## What the numbers mean

| Field | Meaning |
| --- | --- |
| `vwap` | Average price over the levels actually eaten. Not the touch, not the ticker. |
| `slippage_bps` | `vwap` against the mid, in basis points. Always positive on both sides. |
| `fee_bps` | Your fee *per side*. Default 10 (0.10 %), Bybit's standard spot taker fee. |
| `total_cost_bps` | `slippage_bps + fee_bps`. The cost of *this* order. |
| `fee_bps_round_trip` | `2 × fee_bps`. The bar any strategy has to clear. |
| `quantity` | Base units, rounded down to the venue's lot step. |
| `filled_usd` | `quantity × vwap`. Slightly less than the size you asked for, because of the rounding. |
| `complete` | `false` when the book ended before the size did. The numbers then cover what rested there. |
| `reject` | The first venue rule this order breaks — `zero_qty`, `below_min_qty`, `above_max_qty`, `below_min_amount`, `above_max_amount` — or `null`. |
| `capacity_usd` | The largest size whose *worst* level is still inside `budget_bps`. |

## The ceilings are per pair, not per asset

This is the part that catches people. `list_instruments` on the live venue, one
minute apart:

| Pair | Market-order ceiling | Limit-order ceiling | Minimum order |
| --- | --- | --- | --- |
| `BTC/USDT` | 120 BTC | 230 BTC | 5 USDT |
| `BTC/USDC` | 24 BTC | 230 BTC | 5 USDT |
| `WBTC/USDT` | 0.3659 WBTC | 230 WBTC | 5 USDT |
| `BTC/USD` | 0.5327 BTC | 230 BTC | 5 USDT |

Same asset, four ceilings, and the market one is not the limit one. A 200 BTC buy
is a perfectly good limit order and a rejected market order:

```json
{ "accepted": false, "reject": "above_max_qty",
  "hint": "The quantity is above the venue ceiling of 120; split the order." }
```

Any sizer that assumes "BTC has a 230 ceiling" is wrong on three of those rows.

---

## Install

```bash
pip install mcp-batch-slippage-bybit
```

Or from this repository:

```bash
git clone https://github.com/tordagaz-ops/batch-slippage-bybit
cd batch-slippage-bybit
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_batch_slippage          # stdio, for an MCP client
MCP_LOCALE=ru python -m mcp_batch_slippage
```

Client configuration:

```json
{
  "mcpServers": {
    "batch-slippage-bybit": {
      "command": "python",
      "args": ["-m", "mcp_batch_slippage"],
      "env": { "MCP_LOCALE": "en" }
    }
  }
}
```


## Deploy to Render (free)

The repository ships a `render.yaml` Blueprint, so the server runs on a public
HTTPS URL with no API key, no card and no Docker step.

1. Open the Render dashboard and press **New -> Blueprint**
   (<https://dashboard.render.com/blueprints>).
2. Connect GitHub and give Render access to this repository.
3. Select the repository and press **Apply**. Render reads `render.yaml`:
   build `pip install .`, start `python -m mcp_batch_slippage`, health check `/health`.
4. When the first build finishes (2-4 minutes), open the URL Render shows:
   `https://batch-slippage-bybit.onrender.com`.

That page is the human view of the server: it lists every tool. The MCP endpoint is
`https://batch-slippage-bybit.onrender.com/mcp` (Streamable HTTP), so a client entry looks like:

```json
{"mcpServers": {"batch-slippage-bybit": {"url": "https://batch-slippage-bybit.onrender.com/mcp"}}}
```

`curl https://batch-slippage-bybit.onrender.com/health` answers with the tool count, which is the
quickest way to prove the deployment is alive.

Free-plan notes: the instance sleeps after 15 minutes without traffic, so the next
request takes about 50 seconds; 512 MB is enough for this server. If you rename the
service or attach a domain, also update `MCP_PUBLIC_HOST` in `render.yaml`, or the
Host check answers `421`.

## Docker

```bash
docker build -t batch-slippage-bybit .
docker run -i --rm batch-slippage-bybit                     # stdio
docker run -p 8000:8000 -e MCP_TRANSPORT=http -i batch-slippage-bybit
```

---

## The five tools

Every tool answers with a dict. A failure is `{"error": "<code>", "message":
"<localized text>"}`; a partial answer carries `unavailable` and `partial_note`.

### `batch_slippage` — many pairs, many sizes, one call

The flagship. Up to 12 pairs × 8 sizes = 96 rows from one round trip's worth of
requests: one whole-market instruments call (cached for ten minutes) plus one
order book per pair, fetched concurrently under a six-second budget.

```json
batch_slippage(
  symbols=["BTC/USDT","ETH/USDT","SOL/USDT","XRP/USDT","DOGE/USDT","PEPE/USDT"],
  sizes_usd=[1000, 10000, 100000],
  side="buy", fee_bps=10
)
```

Measured on 2026-11-26, 18 rows, all complete, in one call:

| Pair | 1 000 USD | 10 000 USD | 100 000 USD |
| --- | --- | --- | --- |
| BTC/USDT | 0.008 bps (1 level) | 0.008 bps (1) | 1.220 bps (20 levels) |
| ETH/USDT | 0.029 | 0.127 (5) | 3.650 (40) |
| SOL/USDT | 0.705 | 0.705 (1) | 4.068 (5) |
| XRP/USDT | 0.526 | 3.102 (5) | 6.958 (9) |
| DOGE/USDT | 2.634 (2) | 4.719 (4) | 9.293 (9) |
| PEPE/USDT | 2.846 | 5.263 (2) | 11.956 (7) |

Add the 10 bps fee and the worst row of that table is **21.956 bps** — 2.2 dollars
of cost on a 100 000 dollar PEPE order, of which 2 dollars is the fee.

Each row carries the venue's verdict next to the price:

```json
{
  "symbol": "BTC/USDT", "requested_usd": 1000.0,
  "vwap": 60825.1, "quantity": 0.01644, "quantity_sent": 0.016665,
  "filled_usd": 999.94, "slippage_bps": 0.008, "fee_bps": 10.0,
  "total_cost_bps": 10.008, "levels_used": 1, "complete": true,
  "reject": null, "qty_step": 1e-06, "min_qty": 1e-06, "min_amount": 5.0
}
```

`quantity_sent` is what the walk wanted; `quantity` is what Bybit would take
after rounding down to the lot step. They differ in the sixth decimal on BTC and
they are the reason `filled_usd` is 999.94 rather than 1 000.00.

### `plan_slices` — one order, several children

Given a target and a cost budget, how do you actually get it done? Children run
in sequence against the same book, so child *k* sees only what children 1…*k*−1
left behind — which is exactly what a series of market orders does.

```json
plan_slices("BTC/USDT", target_usd=1_000_000, budget_bps=20, max_slices=5)
```

Measured: 5 children of 200 000 USD, every one inside the 20 bps budget, mid
60 825.05, spread 0.016 bps.

| Child | Size | Avg price | This child | Cumulative |
| --- | --- | --- | --- | --- |
| 1 | 200 000 | 60 834.67 | 1.582 bps | 1.585 bps |
| 2 | 200 000 | 60 841.93 | 2.776 | 2.181 |
| 3 | 200 000 | 60 850.56 | 4.194 | 2.852 |
| 4 | 200 000 | 60 855.42 | 4.993 | 3.388 |
| 5 | 200 000 | 60 859.68 | 5.694 | **3.850** |

Two things to note. The children get worse as they go — that is the book, not a
rounding artifact. And the *cumulative* column is the one that decides whether the
plan is worth running: 3.85 bps of slippage on 1 M is 385 USD, against 2 000 USD
of fees.

The same pair, same minute, at two sizes:

| Size | Slippage | Levels eaten | Complete |
| --- | --- | --- | --- |
| 1 000 000 USD | 3.847 bps | 76 | yes |
| 5 000 000 USD | 11.099 bps | 192 | yes |

At 5 M the book is 192 levels deep and the cost has tripled. `capacity_usd`
reported **4 723 813 USD** as the largest size still inside 20 bps — the answer to
"how much can I do before the cost changes character".

### `check_order` — will the venue take it?

One quantity, one price, every rule applied in the order the venue applies them.
A rejected order is an *answer*, not an error: the tool returns `accepted: false`
with the rule and a sentence explaining it.

```json
check_order("BTC/USDT", quantity=0.00005)
→ { "accepted": false, "reject": "below_min_amount",
    "notional_usd": 3.04,
    "hint": "The order is worth less than the venue minimum of 5 USDT.",
    "notes": ["The smallest order the venue accepts on this pair is 5 USDT, about 0.000083 of the base coin."] }
```

```json
check_order("BTC/USDT", quantity=0.05)
→ { "accepted": true, "price": 60825.1, "price_source": "ask", "notional_usd": 3041.26 }
```

`price_source` is `ask` for a market buy, `bid` for a market sell, `mid` for a
limit order and `caller` when you supplied the price. Valuing a market buy at the
mid would understate its size by half a spread — the exact error this server
exists to avoid.

### `list_instruments` — what is worth sizing at all

466 spot pairs with their filters and 24-hour turnover, ranked by turnover. On the
live venue, **18 of 466** pairs cleared 10 M USD of daily turnover; the rest are
pairs you would never send a market order to.

```json
list_instruments(search="BTC", limit=3)
→ BTC/USDT   turnover 1 446 233 773   spread 0.016 bps   ceiling 120   min 5 USDT
  BTC/USDC   turnover   141 006 947   spread 0.016 bps   ceiling  24   min 5 USDT
  BTCRL/USD  turnover     1 230 005   spread 5.020 bps   ceiling   3   min 5 USDT
```

### `list_venues` — who is answering

```json
list_venues()
→ { "default": "bybit", "count": 1,
    "venues": [{ "name": "bybit", "depth_limit": 200,
                 "probe": { "ok": true, "latency_ms": 807,
                            "pairs": 466, "instruments": 466 } }] }
```

---

## Why Bybit, and why `venue` is still a parameter

The product of this server is *one venue's* order sizing: its 200-level depth cap,
its per-pair lot filters, its 5 USDT floor and its split between limit and market
ceilings. Those rules **are** the answer, so a generic multi-venue sizer would have
to flatten them into something weaker — and the flattened version is wrong on
three of the four BTC rows above.

The contract, however, never says "bybit". Every tool takes `venue` and validates
it against `VENUE_NAMES`. Adding an exchange is one adapter class (three public
endpoints: tickers, instruments, orderbook) and one line in that tuple, with no
change to a single parameter or response field. One adapter today, no repository
per exchange ever.

## Errors

| Code | When |
| --- | --- |
| `empty_symbols`, `empty_symbol`, `invalid_symbol` | Nothing usable was passed as a pair. |
| `too_many_symbols` | More than 12 pairs in one batch. |
| `empty_sizes`, `too_many_sizes`, `bad_size` | The size list is empty, longer than 8, or not positive. |
| `invalid_number`, `invalid_limit` | A number that is not a number, or outside its range. |
| `bad_side`, `invalid_order_type`, `invalid_sort` | An option outside the allowed set. |
| `unknown_venue` | A `venue` this server has no adapter for. |
| `unknown_symbol` | The venue does not list the pair for spot trading. |
| `no_data` | No pair in the batch produced a usable answer. |
| `no_book`, `no_instrument` | The pair has no depth, or no published lot filters. |
| `timeout`, `network_error`, `upstream_unavailable`, `upstream_rejected`, `bad_payload` | The venue misbehaved. The request was fine. |

A venue failure never raises: it lands in `unavailable` with its code and detail,
and the rest of the batch is returned.

## Tests

```bash
pytest                # 256 offline tests, no network
pytest -m live        # 12 tests against the real Bybit spot API
```

Five layers, and each one catches what the one above it cannot:

| Layer | What it proves | Count |
| --- | --- | --- |
| `test_unit.py` | The arithmetic on a hand-built book whose mid is exactly 60 000, the lot-rule reducer, the adapter against a real recording, the three-language catalogue | 110 |
| `test_tools.py` | Every tool through the SDK's in-memory transport: payload shape, validation, partial results, locales, concurrency | 78 |
| `test_e2e.py` | The real process over stdio: handshake, `tools/list`, annotations on the wire, error payloads, `MCP_LOCALE`, a junk transport | 26 |
| `test_hosting.py` | The port a platform assigns, `/health`, the landing page, and mcp over http | 41 |
| `test_live.py` | The real API: 466 pairs, a 3-pair batch, cost monotonic in size, dust rejected, 200 BTC refused as a market order and as a 12 M limit order | 12 |

`tests/fixtures/venues.json` is a real recording, trimmed to six pairs and forty
levels per side so it can live in the repository. `_record.py` refreshes it.

## Design notes

- **Quantities round down, never up.** Rounding up is the one thing a venue will
  reject; `Decimal` with `ROUND_DOWN` makes that structural, not a convention.
- **Slippage is always positive-as-cost.** A buy above the mid and a sell below it
  are both reported as a positive number of basis points, so the two sides of a
  book are comparable.
- **Prices round to ten significant digits, not six decimals.** PEPE trades near
  0.0000041; six decimals would turn its price into 0.000004, a 3 % error in the
  number the caller came for.
- **One gather budget, not one per call.** `GATHER_TIMEOUT = 6 s` covers the whole
  batch, so a twelve-pair call cannot take twelve times as long as a one-pair
  call. Books are fetched four at a time.
- **Instruments are cached for ten minutes, books for two seconds.** Lot filters
  change when a pair is delisted; depth changes every block.
- **A rejected order is not an error.** `check_order` answering `accepted: false`
  is a complete answer to the question asked.

## Locales

| `MCP_LOCALE` | Effect |
| --- | --- |
| `en` (default) | English tool titles, descriptions, notes and errors. |
| `es` | Spanish. |
| `ru` | Russian. |

The three catalogues hold the same key set — a test fails if they drift — and an
unknown locale falls back to English rather than failing.

## Free, and donations welcome

This server is free: every tool can be called without payment, registration or
an API key. If it saves you time or money, you can send a donation -- it goes
straight to the developer, with no platform in between.

| Network | Asset | Address |
| --- | --- | --- |
| Base | USDC / ETH | `0x832e9e0FC60c35A07cf80846A9eD27aa7cb4F637` |
| Ethereum | ETH | `0x832e9e0FC60c35A07cf80846A9eD27aa7cb4F637` |

Nothing in the code is gated on donations: no telemetry, no licence check, no
expiring demo. The whole source is MIT-licensed.

## Licence

MIT. See [LICENSE](LICENSE).

TDQS

A3.7/5.0

Scored across 5 tools

Disambiguation4/5

Each tool occupies a distinct slot: discovery (list_instruments, list_venues), validation (check_order), batch depth scan (batch_slippage), and order decomposition (plan_slices). The only real adjacency is between batch_slippage and plan_slices, both of which walk the order book, but the descriptions clearly separate 'grid of pairs x sizes' from 'split one parent order into children.'

Naming Consistency4/5

Four of five names follow a clean snake_case verb_noun pattern (plan_slices, check_order, list_instruments, list_venues). batch_slippage breaks the pattern by being a bare noun phrase, a minor but noticeable deviation within an otherwise uniform set.

Tool Count4/5

Five tools is a tight, well-scoped surface for a Bybit slippage/planning server, with no filler. list_venues is the weakest link given only one adapter exists today, but its probe mode gives it a real function.

Completeness4/5

The read-only analytics lifecycle is well covered: find instruments, validate venue rules, price sizes across pairs, and build a sliced execution plan with cumulative cost. Gaps are minor, though there is no direct single-pair/single-size quote outside the batch grid and no cross-venue comparison despite the venue abstraction.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues