11 Commits
Author SHA1 Message Date
mika@stocksharp.com 47fcbdf055 Match orders against the book, and leave inventing one to emulation
The engine's job is to reconcile real orders against a real book. It was also making
the book up, and what it made up was wrong in ways that cost money.

A quote states where the market is. Each one was written in as a level and the ones
before it kept, so a market walking one way left every price it had ever quoted
resting in the book while the touch stayed where the walk began: three falling quotes
and the book held a bid above its own ask. Past the trim depth the stale side froze
there for good while the other tracked away without bound.

A print says a trade happened. It was written in as a resting level, on a side guessed
when the feed did not say, at a volume of one when the print carried none; on an empty
book a single trade conjured both sides of a market with the far side a made-up spread
away; and a print at or through the touch was written opposite at the price of the
print, which crosses the book on purpose. Then it trimmed - and the trim could not tell
an invented level from one the venue had stated, sparing only levels holding a client's
own order, so every print cut the venue's real book to five levels a side. The matcher
subscribes to ticks, so that is what the live book has been doing.

An order asking for more than the whole opposite side got the book extended past its
worst level, a step apart, doubling volume each time, and traded through it: five lots
offered, fifty asked for, fifty filled. That is replay, and the emulation asks for it
by name; the engine had it on by default and the venue never turned it off.

A resting order the market moved through was filled for its whole balance with no
level consumed and no counterparty.

An instrument whose venue never states a price step has one guessed from the first
price quoted. The guess was written into the security definition the venue sent - kept
by reference, so in the venue it is the feeder's own object - and it was written
whether or not the venue had stated a step, because the gate was "have we guessed yet"
rather than "were we told".

All of it goes. What a quote still tells the engine is whether the instrument may be
traded; what a print still does is check the stops waiting on that price; extending a
book happens only when asked. Building a book out of quotes and prints was already the
emulation's own work, done correctly there - it moves the level instead of leaving the
old one behind - and filling a resting order without a counterparty joins it. The
knobs that bounded and spaced what the engine invented go with it, along with a trim
that had no caller.

What stays is matching: folding an incremental feed into the book the engine holds,
keeping client orders across a venue snapshot, stops, margin, and refusing an order
the book cannot price - which after this is the only thing separating "there is no
market" from "this order is free".

The two tests standing watch over the emulated book asked only that it stay under a
level count. It always did: a book pinned to the first price it ever saw is one level
deep. They ask now that the touch be the last thing quoted and that the sides have not
crossed.
2026-08-25 03:33:59 +03:00
mika@stocksharp.com 735a0e701c Book each maker of an internal cross for what was taken from it
The volume a resting order gave up was computed while consuming it and then thrown
away: the book returned only the orders a level had held, and the adapter worked the
traded volume out afterwards from a balance the consumption had already decremented.
A maker eaten down to its last lot was therefore booked a trade of zero volume, its
position never moved, and downstream the inventory book stayed skewed by the whole
amount for good, because a zero-volume trade is dropped. Orders sitting at a touched
level that the match never reached were booked a phantom trade for the same reason.

The consumed volume now leaves the match with the fill that produced it: ConsumeVolume
yields a MatchFill per resting order - which order, how much of it was taken, what was
left - and MatchTrade.CounterOrders becomes CounterFills. Each maker is booked exactly
what the taker took from it, and an order the match never reached raises nothing.
2026-08-22 09:45:25 +03:00
mika@stocksharp.com 35aee4771e Cache user order volume per price level
TotalVolume is read for best quotes and every order book snapshot. Keep the aggregate user-order balance in sync on add, replace, remove, and consume so those reads no longer traverse the linked list.

Centralize resting-order balance changes in OrderBookLevelImpl and cover mixed market/user volume, partial fills, cancellation, and full fills. This follows the existing invariant required by the cached side totals: balances of resting orders are mutated by the order book.
2026-08-02 02:33:06 +03:00
mika@stocksharp.com 300093c652 Remove per-snapshot allocations from the matching order book 2026-08-01 23:04:55 +03:00
mika@stocksharp.com 34920397ee Fix order book volume accounting on order replacement 2026-07-21 22:18:34 +03:00
Tazeem Mahashin 18885c0097 Fix FIFO ordering after interior cancellations 2026-07-20 11:32:42 -04:00
mika@stocksharp.com 748006938f Emulation: bound the synthesized matching-engine order book to MaxDepth
The decomposed matching engine synthesizes an order book from ticks/Level1 when there is no real order-book
history (MatchingEngineAdapter.ProcessTick/ProcessLevel1 -> OrderBook.UpdateLevel). It added a new level per
distinct price and never removed stale ones, so replaying a long varied price stream - as a tick backtest
does - grew the book without bound (hundreds of thousands of OrderBookLevelImpl plus the downstream
ExecutionMessages they drive), accumulating into multi-GB heap growth that eventually exhausted memory and
crashed the test host near the end of the full suite.

Restore the MaxDepth cap the monolith MarketEmulatorOld already applied: OrderBook.TrimSynthesizedDepth drops
the farthest synthetic levels beyond MaxDepth after each synthesized UpdateLevel, and never removes levels
that hold real registered user orders - only their synthetic MarketVolume is cleared. MatchingEngineSettings
gets a MaxDepth (default 5) mirroring MarketEmulatorSettings, and MarketEmulator syncs it into the engine.

Add tests asserting the tick- and Level1-synthesized book stays within MaxDepth; the fill-price tests (fills
near the current price, not a stale extreme) stay green.
2026-06-21 23:05:20 +03:00
mika@stocksharp.com e67deb22e1 OrderBook: stop snapshotting the whole book on every consume
ConsumeVolume copied the entire quotes dictionary with quotes.ToArray() on every
match, just so emptied price levels could be removed while iterating. That is a
per-match allocation proportional to book depth on a hot path.

Iterate the live dictionary instead and collect the emptied prices, removing them
in a finally block. The dictionary is never mutated during its own enumeration,
and because disposing the iterator runs the finally, the removal still happens
even though the matcher abandons the enumerator early (it breaks out as soon as
the order is filled) - which is the reason the snapshot was introduced in the
first place. The only remaining allocation is the affected-orders list that is
returned to the caller, and the small removal list, allocated lazily only when a
level is actually emptied.

Behaviour is unchanged: 203 matching-engine and market-emulator tests pass.
2026-06-16 00:07:13 +03:00
mika@stocksharp.com af7255490c Fix order matcher book consumption 2026-06-14 17:18:57 +03:00
mika@stocksharp.com 0bcf594d25 Use Ecng Common extensions across codebase
Replace standard .NET APIs with Ecng.Common equivalents:
- Math.Min/Max/Abs/Round → .Min()/.Max()/.Abs()/.Round()
- string.IsNullOrEmpty → .IsEmpty()
- string.Format → .Put()
- Encoding.UTF8 → .UTF8()
- Enum.GetValues → Enumerator.GetValues<T>()
2026-03-29 17:04:00 +03:00
mika@stocksharp.com db29e70fde Extract MatchingEngine project from Algo.Testing
Move 9 core matching engine files (OrderBook, OrderMatcher, PortfolioManager,
MarginController, OrderLifecycleManager) into standalone MatchingEngine project
with namespace StockSharp.MatchingEngine. MarketEmulator stays in Algo.Testing
and references MatchingEngine. Update all solution files and test references.
2026-03-05 06:25:55 +03:00