A run whose market data was all refused for lack of history waited for
its first subscription forever. It ends now when it starts with all the
market data asked for refused. Whether any is left is decided when the
run starts, never at a refusal: a strategy asks for one series after
another, so the refusal of a pair's first leg comes before its second
is asked for, and stopping there ended a run that had the second leg's
history. A run with nothing asked for yet keeps waiting, as a host may
start the strategy after the run, as the Studio runner does.
Such a run ends with an error rather than as a finished one: Connector.
Error says the market data is missing, StopError keeps it for a host
that looks once the run has stopped, and the progress does not reach
100. A run stopped on a failed subscription (StopOnSubscriptionError)
ends the same way. A strategy that asks for no market data, or whose
market data was all refused, is stopped with that error by
StrategyHelper.StopIfNoMarketDataAsync once it has started, which
ExecAsync and the optimizer use: ExecAsync reported such a run as
completed or waited for it forever, and the optimizer's check ran
before the connector was connected and left the iteration waiting.
Partial history, which the tests never fed a run, had more of the same:
- a refused subscription kept the strategy offline for the whole run,
so a run that went on with the data it had sent no order. Only a
subscription refused before it got going is left out; one that fails
after it went online still takes the strategy offline, its data gone;
- ticks only a generator made never started the replay;
- a series stored only outside the run's dates stood in for the run's
own data, so five-minute candles were not built from the run's
one-minute candles and none arrived;
- a subscription added during the run made the replay send again what
it had already sent at that moment, and with the cache of days it got
nothing until the next day, the cache knowing a day by its date alone;
- history that ended before the run's stop left its progress at a
fifth. A run that runs out of history reports the whole way now; one
disconnected halfway still reports where it stopped, which the
optimizer goes by to stop the strategy of an iteration it cancels;
- an instrument whose history ended before the run's kept its last bid
and ask, so orders on it filled in any volume at a day-old price. Once
its last bar is handed over its market closes: a market order finds
no price, a limit waits, a position keeps the value of the quotes the
market closed with, and more history opens the market again;
- a day without history moved the strategy's clock twice, just after
midnight, and the clock reached the stop only after the run had
stopped. The replay walks such a day at the pace of the time-frame
candles and generators it still replays, the emulator hands the clock
on with every bar it releases, and the run's last moment is its stop
date, so timers and time rules fire through the gaps. Ticks, quotes
and the order log keep no pace, and the days after every history has
ended are marked only where they begin, so a long stop after the
history costs no more than it did.
Every increment went through the increment builder into a whole new book, which the engine then
rebuilt from scratch: the cost of a frame grew with the depth of the book, and a venue like Binance,
which states 1000 levels and keeps every level it ever changes, sends ten frames a second per
instrument. The broker stand's matcher spent its CPU on this with no order in it.
Once a whole book stands, an increment now updates only the levels it names (OrderBook.UpdateLevel);
a client order resting on a level stays, as before. Snapshots, snapshots stated in parts and
positional books still go through the builder, and an increment that arrives while no whole book
stands is still not folded. On a book of 700 to 3600 levels a side an increment costs 0.02-0.05 ms
instead of 1.3-9 ms.
A venue tells an account what it holds: money, positions, their entry
prices and what each position has gained or lost. The emulator reported
only the account total, and only when an order changed something - and
in a backtest even that never arrived. A position adapter recounting
positions from trades answered the portfolio lookup itself, so the
emulator had no portfolio subscription and every report it made about
the account was dropped. A strategy that manages a basket by the
floating profit of its positions could not work in a backtest.
- The matching engine reports a position with its floating profit,
marked at the price it could be closed at, with every fill and again
whenever the market moves that price. The market emulator of a
backtest reports it with every fill and revalues open positions
before each bar it hands over, so a subscriber acting on a bar reads
the positions that bar produced, without a report for every price in
between.
- Positions are no longer recounted around the emulator, and the
portfolio lookup reaches it. An account the emulator opens starts
with the money of the portfolio it stands for instead of zero.
- An order a subscriber sends in reaction to a message runs before the
rest of that message's batch is delivered, so the account reports the
batch still holds about an account the order changed are dropped
instead of arriving after the newer ones.
Reporting the positions on every bar sends portfolio names and security
ids through lookups that compared them by the invariant culture, which
on .NET runs through ICU: hashing a portfolio name and checking whether
a security is the all-securities placeholder took more time than the
rest of handling a position report. They are identifiers and now ignore
case ordinally, so names that differ by a character the culture skips,
such as a soft hyphen, are no longer taken for the same name. This
covers the emulator's portfolios, the in-memory position storage, the
portfolio-to-adapter map, the optimizer's portfolio copies,
Security.ToSecurityId and IsAllSecurity.
A backtest now raises PortfolioReceived as live trading does.
A market order names no price, so only the book can give it one. Sent against a
side holding nothing - an empty book, or a book quoting only the order's own
side - it produced an Active row and then a Done row with the balance still
equal to the volume and no error at all, which reads exactly like an order that
filled as far as it asked to. A strategy could not tell that it had not traded,
let alone why.
The refusal was already written, and switched off: the check that an order with
no price cannot be paid for sits behind an early return taken when money is not
being checked, and money is not checked by default. Whether a market exists is
not a question about money.
Two neighbours stay as they are, and are now pinned: an order the book fills
only part of did find a market, so it ends Done with what it bought; a limit
order carries its own price and rests in an empty book.
Gone with it: a setting naming this behaviour that nothing ever read, and a
variable in the matcher that computed whether anything traded and did nothing
with the answer.
Five things in the core promised behaviour nothing held them to, and the suite
was green on all of them for one reason: it checked that a value is carried
correctly, never that it changes an outcome.
A percent activation price is a distance from the market, and the contract says
the server snapshots the price at registration. Nothing read the flag, so the
raw number became the trigger - a buy stop written as "five percent" fired on
the first print and a sell stop written the same way rested at 5 and never fired
at all. The only test naming the flag round-tripped it through serialization,
which passed precisely because the value is stored correctly. Its two sibling
flags each had a behavioural test; this one never got one. It is now snapshotted
against the last price the venue printed - the only stream a stop ever fires
against - with registration refused outright when there is nothing to snapshot.
Take profit turns out to have carried none of the three flags, so both halves of
the protective pair go through one path, and a structural test walks the
interface so a fourth flag cannot be added without being honoured.
The GPU comparison allowed 2.5% of the compared value, five orders of magnitude
above what float32 can lose. It is now formed from the epsilon, the window a
kernel accumulates over and the scale it works at - and five kernels turn out to
compute something else. Jurik seeded its cascades on the first bar where the CPU
seeds them for the whole formation window; Ichimoku trimmed its Senkou B store
to the Kijun length, returning the previous bar's value whenever the two were
equal; VWAP accumulated a whole series in float32; SuperTrend and
NickRypockTrailingReverse pick a branch by comparing a price to a level, which
float32 rounds more coarsely than the step between them.
A candle builder's Timeout was a public setting no code read, its mechanism
commented out - gone, with nothing in any repo setting it. The pair strategy
template declared two securities and traded one - it trades both now.
And Sharpe and Sortino scored five returns spread over a year exactly as they
scored the same five over five days. The class declared Period and derived the
annualisation from it, so it always promised equal spans, but counted every PnL
report as one period and ignored the time it carried. Returns now close on that
grid: an idle period is a return of zero, a period opened with no capital
records none, and the tail waits for its own boundary. Reading time at all
exposed two further things - a report stamped with the default date would have
opened the grid in year 0001 and buried a run under seven hundred thousand empty
periods, measured at 382 times too low on every optimiser iteration, and Period
could be changed while a grid was open. Figures from before are not comparable:
a strategy that reports rarely now scores lower, which is the point.
The suite itself was deciding results by how loaded the machine was. Eighteen
waits had no deadline and hung rather than failed, seventy-two more stood in for
a condition with a sleep, and twenty-two method timeouts were no longer than the
wait inside them. What remains is the kind that must stay: a window held open to
prove something does not happen, a delay that is itself under test, the pacing
of a feed. Eighteen files each declared the same empty TestReceiver and nine
their own CreateSecurityId - those had drifted, four returning a fresh id and
four a fixed one, so they were not merged blindly. StorageTests and
IndicatorTests, at about 3900 and 3600 lines, are split into partial classes by
theme with every fully qualified name kept.
Left as a finding: the ratio grid is fed from two clocks - a position's local
time on one path, the engine's market time on the other - which differ by hours
in a backtest. Putting both on the connector's clock changes which timestamps
MaxProfitDate and MaxDrawdownDate carry, and that is a contract decision.
Every test written during the coverage review, in one commit: 105 files, about 32,000 lines added.
No product code is touched here - what the tests found is repaired in the commit that follows.
WHERE THEY CAME FROM. Three audits read the core and its suite side by side and filed 295 findings.
Each was taken as a claim to be disproved rather than believed: of the defects claimed, most did not
survive a second reading - an unreachable trigger, a promise nobody ever made, behaviour already
covered, and in one case a property the model no longer has, so the test could not be written at all.
What survived is here.
WHAT THE TESTS ARE. Three kinds, and the difference matters.
A hole: behaviour the core has and nothing checked. Most of the new files are this - the adapters
that filter a depth, hold a candle, track a lookup, associate a security or loop a message back; the
message clone that must not share state with its original; the generators behind localized strings
and media names; the round trip of a diagram strategy and of a FIX data type.
A test that proved nothing: a name that promised one thing while the assertion checked another, an
assertion that could not fail, an expected value copied from whatever the code returned that day.
Those were rewritten in place to say what they were named for, and several of them go red doing it.
A defect: a promise the core makes and does not keep. Those tests are red, and they stay red until
the next commit repairs them - a red test is the record of the defect, and there is nowhere else the
record would be read.
HOW THEY ARE WRITTEN. From the promise, not from the implementation: the expected value is what the
caller is owed, never what the method happens to return. Every assertion carries a message saying
what was owed to whom, so a failure reads as a sentence rather than as two numbers that differ.
Claude-Session: https://claude.ai/code/session_01LjT4RKLsz3vBd8eSERZTde
Candle matching caps a fill at the candle's volume and then decides what becomes
of what is left, and the predicate that decides did not name market orders. A
market order for one lot meeting a candle with 0.320 available filled 0.320 and
put the remaining 0.680 into the book at the order's own price, which for a
market order is zero. Nothing took it out again - the sweep that removes stale
levels looks at limit orders only - so a later opposite order crossed it and two
own trades came out sharing one trade id at price zero, which the entity cache
then rejected, as it should. The zero level cost more than that order: the depth
top-up walks up from the worst quote and stops at price zero, so it was silently
off for everything later on that side.
The book matcher already says what should happen here. MatchMarketOrder returns
the remainder with ShouldPlaceInBook false and the order Done - the same terminal
shape a limit order with CancelBalance gets, execute what you can and cancel the
rest. Candle matching now says the same thing.
Releasing what the cancelled balance had blocked was missing on both paths: the
guard named IOC and FOK, and a market order is neither, so the block outlived the
order that made it. In the emulator that only mattered once the remainder stopped
resting; on the book path, where the block is priced at the real touch, it has
been overstating blocked funds for the rest of every run.
The engine named the account on its trades but not on the rows about the order
itself: the registration acknowledgement, the cancel, the replace, and the
failures that answer a transaction it holds nothing for. A consumer routes and
books by account, so each of them had to put the account back from its own
memory of the registration - and the SBE wire drops a row that still names none.
All eight now carry it, and none needed anything fetched: the account is on the
command being answered, on the order the book gave up, or on the stop the
manager cancelled.
The same went for the securities. The engine keeps the definition it is given
and matches against what it derives from it, but never gave it back, so a venue
that had to answer "what do you list" kept a second copy of every definition it
had forwarded. SecurityState now exposes the definition it holds, and the
adapter the list of those that have one - a security it has only ever seen a
book for states none and is not listed.
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.
IPortfolio and IPortfolioManager had one implementation each, and substitution
through them did not work: the adapter narrowed the manager back to the concrete
type before wiring it, so a foreign one got neither a margin controller nor a price
source and could compute neither margin nor unrealized result. An interface that
cannot be implemented by anything else is a contract with itself.
The adapter now holds an EmulatedPortfolioManager it creates and never replaces,
wired in the constructor, and the narrowing step is gone with the interfaces.
PositionInfo and TradeProcessingResult, which shared the interfaces' file, get files
of their own; the documentation the interfaces carried moves onto the members that
implement it.
TryGetPortfolio is added beside GetPortfolio, which creates on a miss - so asking
whether the book holds an account was writing to it. A caller that wants to read an
account it may not have now has a lookup that answers without opening one.
One test comes with them. ValidateFunds answers "no objection" for an account the
book has never heard of, which reads like a hole: with the money check on, an order
naming an unknown account would be paid for by nobody. It is not one - the register
path opens the account before the funds check runs, so the check sees it holding zero
and refuses the order - and now something says so.
An account's unrealized result is computed against the prices its open positions
could be closed at, and those prices reach the portfolio book through a mark-price
source. That source was assigned in one place only - inside the funds check, after
the line that returns early when money checking is off.
So it was assigned no earlier than the first order registration, and never at all
when the venue does not check money. Until then every open position revalued to
nothing: a backtest showed equity that did not move until a position was closed, and
a venue that restarts with positions read back from its record told each client what
it held without them.
It is wired when the book is, in the constructor and again when a book is assigned,
so what an account is worth no longer depends on a setting about order acceptance.
The money row itself was written twice, once by the engine and once by the emulator
wrapping it, and the emulator's copy was the one still stating a zero unrealized
result. There is one now, and both call it.
An account's money was its opening balance plus what it had realized: an open
position that moved against it changed nothing. So a client deep under water
reported the money it started with, the funds check never saw the loss, and it
could keep opening more - and a margin call could not exist in that model, because
nothing ever moved against an account until it closed the position. The engine
carries MarginCallLevel and StopOutLevel already; this is the half that was never
built. In a B-Book the broker is the other side of those trades, so it is the
broker's money.
Positions are now revalued at the price they could be closed at - the bid for a
long, the ask for a short - and that revaluation goes into TotalPnL, so both what
the funds check compares against and what the client is told as CurrentValue
include it. What is blocked stays the position's cost at average price, so the
cost and the change in value are counted once each: an account that opened with
2000, bought 10 at 101 and watched the market halve has 1490 of equity, 1010 of it
committed, and 480 left - which is why a further order for 500 is now refused
where it used to be accepted.
The price is read when the number is asked for, not pushed into every portfolio on
every book update, and it is read without creating state for an instrument the
engine has never seen. A position in an instrument nobody has quoted is worth what
it cost: no price, no revaluation, and nothing throws.
The tests: a long that fell and a short that rose each leave less to trade with -
both go red again if the revaluation is taken back out - plus two that hold the
fix from overreaching, since an unpriced position must not invent a loss and a
position in profit must not cost the account anything.
A group cancel that closes positions materialises one order per position, and every
one of them carried the group request's transaction id. Two closes standing at once
were indistinguishable, and whoever keyed fills by that id booked both against a
single order and lost the other. Each close now takes an id of its own.
Such an order is built inside the engine and crosses no caller on its way in, so
nothing downstream holds the account to put back on its rows: its executions went out
naming no portfolio and were booked against nobody. The rows a close raises are now
stamped with the account and the instrument the order was built for when they carry
none, and an order's own fills state the account outright. The legacy emulator, which
materialises those orders the same way, gets the same two fixes.
The order a stop turns into when it fires was built without a transaction id, so
everything raised for it went out with an original transaction of zero: fills nobody
could attribute, which downstream either broadcast to every session or delivered to
none, and a resting limit order filed as anonymous market volume, because the book
branches on that id to tell a client order from the venue's own flow.
The derived order now continues the stop's own transaction - the only id the caller
ever issued, and therefore the only one its executions can be attributed to. With the
resulting order reporting under that id, the separate Done row the trigger used to
raise for the stop is no longer needed: the registration that follows it is the same
order's lifecycle.
When a taker crossed a resting order, the counter loop emitted the trade, the position
change and the portfolio row - and no order state at all. The session that placed the
maker saw an order that stayed active for good, and every map downstream keyed on a
final state grew by one per crossed maker. Worse, an order consumed in full left the
book but stayed in the order manager: it kept turning up in the active list, in status
answers and in group cancels, long after there was nothing left of it.
The resting order's own state now goes out ahead of its trade - Active with what is
left, Done when the fill took the last lot - and an order filled to nothing is removed
from the order manager along with its place in the book.
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.
The depth the engine synthesizes for an order too large for the visible book was
decided by comparing the order's price against the opposite best. A market order
carries no price, so that comparison read zero: a market sell looked crossing (0 is
below every bid) and got the depth it needed, while the mirrored market buy looked
non-crossing (0 is below every ask) and got none. The same order on the two sides of
one book filled a hundred lots and one lot.
A market order crosses by definition, whichever side it is on, so the depth is now
synthesized for it without consulting a price it does not have.
The engine kept portfolios in a case-sensitive map while everything around it
matches account names without regard to case. An order that spelled the name
differently from the message that funded it opened a second, empty portfolio beside
the funded one: the money was in one book and the position in another, and once the
second book existed every further order on it was refused for want of funds that
were sitting next door.
One spelling, one account: the map now compares names the way the rest of the
engine does.
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.