Skip to content

feat(ts-sdk): estimate a taker order's fill against the book - #317

Open
0zzy-o wants to merge 1 commit into
mainfrom
feat/estimate-fill
Open

0zzy-o wants to merge 1 commit into
mainfrom
feat/estimate-fill

Conversation

@0zzy-o

@0zzy-o 0zzy-o commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

What

estimateFill(book, side, size, limit?) estimates what a taker order of size would fill against an Orderbook. It walks the opposite side best-first (asks for a long, bids for a short) and stops at limit, which is a market order's protective price. It returns:

Field Meaning
filled Base the book fills within limit (≤ size)
price The price that fill clears at, were this the batch's only order. Undefined when nothing fills
slippagePct How much worse price is than the best level, in percent
exhausted The walk ran off the levels it was given while still inside limit. On a depth-truncated book, filled is then a lower bound

The trading app uses it to warn before a market order that would fill only partly, or not at all, within its slippage cap. Today the IOC remainder is canceled and the user is told nothing.

How

price follows the batch clearing rule (doc/protocol/orderbook.md, Clearing), not a volume-weighted average. Every match in a batch clears at one price, and a market order never sets it. The clearing range runs from the last level matched to the first level left unmatched (the same level when only part of it was taken). It settles at the midpoint, never past the order's own limit.

So the whole fill pays at least the last level reached. With asks of 1 @ 100, 2 @ 101 and 5 @ 103:

Order price A VWAP would say
Buy 0.5 100 100
Buy 1 (best level taken whole) 100.5 100
Buy 2 101 100.5
Buy 5, limit 102 (fills 3) 102, capped from 102.5 100.67

Assumptions: the order is alone in its batch. Other orders in the same batch can change both the fill and the price. Grouped levels make prices approximate to the grouping.

Testing

npx vitest run src/sync/order-preview.test.ts covers part-taken and whole levels, the limit cap, a level already past the limit, shorts, running off the levels given, and an empty side.

🤖 Generated with Claude Code

estimateFill(book, side, size, limit?) walks the opposite side best-first
and stops at a market order's protective price. It returns the base
filled, the price that fill clears at, its slippage against the best
level, and whether the walk ran off the levels it was given.

The price follows the batch clearing rule rather than averaging the
levels: every match clears at one price and a market order never sets
it, so the whole fill pays at least the last level reached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant