7 Commits
Author SHA1 Message Date
mika@stocksharp.com 661fad5eb6 A backtest replays whatever history it has, and says why it ends
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.
2026-10-24 22:31:07 +03:00
mika@stocksharp.com 1071c5efbd Fold a book increment into the matching engine level by level
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.
2026-10-04 02:36:10 +03:00
mika@stocksharp.com 2189594de5 Check that values do something, not merely that they travel
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.
2026-09-19 12:56:18 +03:00
mika@stocksharp.com 0e6b55144a Let the engine state what it knows about the orders and securities it holds
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.
2026-08-29 22:55:58 +03:00
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 1000e4d950 Refuse an order for an instrument the venue has halted
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.
2026-08-22 09:42:50 +03:00
mika@stocksharp.com 7d805c7e26 Add MatchingEngineAdapter with SecurityState and Settings
Message-based matching engine adapter implementing IMessageTransport.
Contains pure matching logic without emulation dependencies:
- SecurityState: per-security state (OrderBook, OrderManager, steps)
- MatchingEngineSettings: minimal settings for matching
- MatchingEngineAdapter: order matching, portfolio management, stop orders,
  L1/tick->orderbook conversion, IncreaseDepthVolume
2026-03-05 19:56:13 +03:00