The engine had a CheckTradingState setting and nothing behind it: the venue's
trading state arrived on Level1 and was dropped, so nothing ever knew an instrument
was halted and every order stood as usual. A stand that had switched the check on
believed it was protected and was not.
The state the venue last stated is now recorded on the security - whatever the
setting says, since recording is not refusing - and an order for an instrument that
is stopped is refused when the check is on, before anything is asked about money.
A market order names no price, and the money check took that zero as the price to
charge for it: required margin came out zero, the available-money check passed for
any non-negative balance, and an account holding nothing could market-buy any size
at all. It also blocked the same-side best - the one price it would never trade at -
instead of what it was validated against.
The order is now charged what it will pay: the opposite best, the ask for a buy and
the bid for a sell. On a side with no quotes there is no price at which the order can
be honoured, so it is refused rather than let through free. Validation moved into
ValidateRegistration, which takes the charged price, and the candle emulator passes
the price the candle fills at, since in candle mode the charge comes from the candle
and not from a book.
Sides.Buy is the enum's default, so every ExecutionMessage that never touched
Side read back as a buy. Nothing said so and nothing could tell the difference,
which is how a rejected sell went out as FIX tag 54=1: the writer emits the tag
unconditionally and had no value meaning "unstated".
Side is now Sides?, and so is IOrderMessage.Side - an order always has one, a
message reporting on an order need not.
Callers split three ways. Where the message is the only source of truth for an
order - materializing one to send to a venue, building one the receiver has not
seen, signing a fill, booking a row into a side of the book - a missing side is
refused rather than defaulted. Where the side is merely descriptive, the absence
travels. Where it was silently invented, it is now stated: the matching engine
and both emulators left it off sixteen order reports, every one of which the
receiver read as a buy.
Storage keeps its layout. The snapshot record is positional and read without
version branching, so the absence rides in the byte the side already occupies -
Sides has two values and the byte has 254 spare. The transaction stream carries
one bit that cannot express absence, so Version72 writes the nullable form while
older files keep being read through the old branch. The order log throws instead:
a row entering or leaving the book always has a side, and a lifted comparison
would have written Sell for one that did not.
FIX omits tag 54 when the side is unstated. A required tag that is absent is
loud; a required tag that is wrong is not.
An internal venue does not come up knowing what is outstanding - it has to be
told, and what tells it is the ordinary execution report the rest of the system
already speaks. Until now such a report was turned into a registration request:
the account was charged a second time for exposure it already carried, the order
was given a new identity instead of the one it is known by, and it was crossed
against the book on the way in. Whatever the engine ended up holding was not the
order that exists elsewhere.
A report is now recognised as state rather than a request when the sender can
say all three things only its owner knows: that the order is active, the
identity it is known by, and how much of it is left. Such an order is seated in
the book exactly as it is, registered with the lifecycle so it can be cancelled
and replaced like any other, and margin is reserved for the remainder - the
account is carrying that exposure whether or not this process was running when
it was placed.
The identity is read from whichever field carries it. The report that registered
an order carries the registration as its own transaction; a later state report
carries it as the transaction it answers - the same two shapes the router
already reconciles when it rebuilds orders from storage. Reading only one of
them would leave the other quietly treated as a fresh request, which is the
failure this change exists to remove.
Nothing is reported back. The order was not registered here, so there is no
request to answer, and an owner handed a registration report for an order it has
held for hours would reasonably read it as a new one. Being told twice about the
same order is ordinary and changes nothing: an identity already in the book is
left alone rather than duplicated.
A fill emits two portfolio rows: how much of the instrument the account now
holds, and how much cash it has. Both went out under SecurityId.Money, so the
first one described a lot quantity and an average price while claiming to be
about money. All three fill paths did it - the aggressor, the matched counter
order, and a resting order swept by the tape - while the portfolio lookup,
which reports the same positions, correctly named the instrument. The two
therefore disagreed about the same account depending on which one you read.
The consequence is not cosmetic. Anything storing these rows resolves the
instrument first, and MONEY@ALL resolves to none, so every position row a
fill produced was dropped on the way to storage: a venue that matches
internally recorded no positions at all. Anything displaying them read a
quantity as a cash balance.
The same row is emitted from three implementations - the engine, the
emulator that wraps it, and the obsolete one the comparison suite pins the
other two against - so all three are corrected together and the suite still
holds them equal.
Restoring a position now keeps the average price it was given. The opening
state carries one, IPortfolio.SetPosition takes one, and it was simply not
passed on, so a restored position started at average price 0 and the first
close realized the entire notional as profit.
The suite that should have caught this could not, and that is fixed here too.
It compares the two emulators against each other and asserts nothing else, so
a mistake both of them make is a mistake both of them agree on: all three
implementations emitted the row as money, every comparison matched, and the
suite stayed green over it for as long as the bug existed.
The two rows now have a contract that is asserted independently of either
implementation - a row carrying an average price describes an instrument and
must name it, a row carrying realized PnL is the account's cash row and must
be money, and a position row must name something. It is checked on the
emitting side, in the subscription every emulator test factory installs, so
it covers every message of every test in all three suites and a test added
later inherits it without having to remember. Reverting the three emitters
alone now fails 50 of the 89 emulator tests, where before it failed none.
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.
Both market emulators created the order-acceptance response without an order state and only set it to Active
when the order stayed resting after matching. An order that filled immediately therefore went from no state
straight to Done and never reported Active, so a consumer that subscribes to the raw emulator output never
observed the order becoming active. Initialize the acceptance response as Active in the matching engine, the
candle-matching path and the legacy emulator's accept path; a rejection, expiry or a full fill still overwrites
it, so every order now passes through Active exactly once while the V1/V2 feature comparison stays in agreement.
A ClosePositions group cancel generated an offsetting order with a freshly generated transaction id, so its
executions reported back against an id the caller never sent and could not correlate. Reuse the group cancel
request's transaction id for the closing order, matching the legacy emulator, so the close executions are
attributed to the request the caller actually issued.
Two early-outs on the per-message matching hot path, which runs millions of times
per backtested month:
- OrderLifecycleManager.GetExpiredOrders/ProcessTime allocated a List on every
call even when no order had an expiry set. Return an empty enumerable when
there are no tracked expiry times.
- MatchingEngineAdapter.CheckLimitOrders read BestBid/BestAsk and scanned the
active orders on every tick/quote. Return immediately when no order is resting,
skipping those reads and the scan in the overwhelmingly common case.
Both fire only when the respective collection is empty, so whenever orders exist
the original path runs unchanged and backtest results are unaffected.
Three problems made own trades land off the candles when backtesting on tick or level1 (spread)
data - visible as buy/sell markers far below/above the price on the chart:
1. The order book synthesized from ticks/level1 accumulated levels and never cleared them, so the
best bid/ask drifted to historical extremes and orders filled at stale prices. Now each tick or
quote replaces the synthesized bid/ask around the current price (ProcessTick/ProcessLevel1).
2. Resting limit orders were matched only at registration and never re-evaluated as the market
moved (unlike stop orders, checked on every tick), so a price trading through a resting limit
left it in the book to fill later at a price the market had already left behind. Add
MatchingEngineAdapter.CheckLimitOrders, run after each tick/quote, executing in full any resting
limit the price has traded through, at the traded price (tick) or the quote mid (level1).
3. A marketable order filled only the fractional synthesized volume at a level and rested the
crossed remainder at a stale price, which a later counter order then matched off the candle.
Give the synthesized touch ample liquidity so a marketable order fills fully in one trade.
Tests: TickMarketOrderFillsAtCurrentPriceNotStaleExtreme, Level1MarketOrderFillsAtCurrentPriceNotStaleExtreme,
FallingTickSweepsRestingBuyLimit, and the integration test BacktestTradesStayWithinCandlesAllModes
(first 7 days of real history, the WPF-sample SMA strategy, candle/tick/level1 modes) which asserts
every own trade fills inside its candle - zero off-candle fills in all three modes.