30 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 0e55039817 Report the emulated account to the connector, floating profit included
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.
2026-10-02 00:14:27 +03:00
mika@stocksharp.com 536abc52b0 Refuse a market order that has no market, and say so
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.
2026-09-19 23:49:12 +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 786837968b Fix matching engine and emulation lifecycles 2026-09-14 18:22:25 +03:00
mika@stocksharp.com ee0aad30e5 One matcher for the emulator, and a fill reported before the state it produced
Three things, all in the path an order takes through emulation.

A FILL COMES BEFORE THE STATE IT PRODUCED. Both matching paths announced an
order final and then announced the trade that had made it final. Anything
holding per-order working state releases it on a final state carrying no trade -
that is how a cancelled or rejected order stops being tracked - so the release
ran first and the trade that followed arrived about an order nobody was holding
state for. The slippage manager is the reader that showed it: it keeps the price
an order was planned at, could no longer find it when the fill came, and so
Slippage was never computed, never stamped on the trade and never accumulated on
the strategy. Five sites had the same inversion; the order of these messages is
a contract and the emulator now states it in a test.

WHAT A MATCH OWES IS WRITTEN ONCE. Emulation matched against a candle and then
wrote out the result with its own copy of the code that writes out a book match:
175 of 187 lines verbatim, ending in 71 that matched character for character.
That copy is why the fix above had to be made five times, and why the two paths
had drifted apart in six ways nobody chose. What a match PRODUCES differs and
stays where it is; what it OWES - the order rows, the trades, the maker side of
each fill, the positions, the portfolio updates - is now EmitRegistrationResult
on the engine, and both callers hand it the MatchResult they were already
producing.

THEN THERE IS ONLY ONE MATCHER. A bar was matched as a single unit by rules of
its own: a limit filled at its own price if the bar's range covered it, a market
order at the bar's midpoint. Nothing rested, nothing was swept, no stop ever
fired, because the only thing that looks at a resting order is the book and
candle mode never fed it. A bar is a summary of prints, so it is now fed back as
prints - open, then the high and the low in whichever order the bar recorded
them, then close - and the book matcher does the matching. The second matcher
and the crossed book it published are gone.

Three things start working: a stop triggers inside a bar, a resting limit fills
after the bar it was placed in, and an order is no longer matched against the
future of its own bar. What does not change is what IncreaseDepthVolume decides:
off, the bar's own traded volume is what the levels a print builds will hold, so
an order still fills only as far as the bar traded. Candle-mode backtests do
return different numbers, because an order fills a bar later and at a price the
bar printed rather than at its midpoint.

The clock had to move first, so ProcessMessage advances time before acting on
the message - forward only, since a strategy stamps its order with the bar it
reacted to and releasing at that stamp would run the clock backwards. Commission
is charged once, where a batch leaves the emulator; it used to be charged inline
on the candle path and swept on two others, and the tick path, which is now
every path, was charged nowhere at all.

No existing test changed. ProcessTick takes the volume its levels hold, stated
at both call sites rather than defaulted, which is what lets the replay say what
the bar held.

4851 tests, the known load-sensitive flakes aside.
2026-09-06 19:51:55 +03:00
mika@stocksharp.com 7370fc16db Cancel a market order's remainder instead of resting it at price zero
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.
2026-09-01 20:35:27 +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 1cb1c5487c Let the engine own its portfolio book
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.
2026-08-24 02:37:31 +03:00
mika@stocksharp.com 72d8ba5d15 Revalue open positions whatever the venue checks
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.
2026-08-23 21:25:18 +03:00
mika@stocksharp.com 050b9eb55e Take an open position's loss out of the money the account can trade with
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.
2026-08-22 09:45:26 +03:00
mika@stocksharp.com c97a354549 Give each group-cancel close its own order id and name its account
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.
2026-08-22 09:45:26 +03:00
mika@stocksharp.com 138dab8a7d Give a triggered stop's order the stop's transaction id
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.
2026-08-22 09:45:26 +03:00
mika@stocksharp.com e0bca985e9 Tell a consumed maker that its order has finished
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.
2026-08-22 09:45:26 +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 76b0bb4274 Deepen the book for a market buy the same as for a market sell
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.
2026-08-22 09:45:25 +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 411b76c00c Charge a market order what it will actually pay
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.
2026-08-22 09:40:19 +03:00
mika@stocksharp.com 3ce575b384 Let an execution say it states no side
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.
2026-08-15 21:14:39 +03:00
mika@stocksharp.com a559b96868 Use shared multicast async invocation 2026-08-13 12:48:37 +03:00
mika@stocksharp.com 80208e9291 Let an order that is already live enter the engine as state
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.
2026-08-03 18:11:23 +03:00
mika@stocksharp.com dce93f7286 Emulator: name a fill's position row after the instrument, not after money
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.
2026-08-02 16:16:01 +03: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 21865c07a2 Emulation: report order acceptance as Active in both emulators
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.
2026-06-20 18:30:05 +03:00
mika@stocksharp.com 235bf9bde1 MatchingEngine: tag position-closing orders with the group request id
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.
2026-06-20 13:40:00 +03:00
mika@stocksharp.com 1999e27064 Emulator matching: skip per-message work when there is nothing to match
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.
2026-06-01 23:51:15 +03:00
mika@stocksharp.com a11dc860ca Emulator: keep tick/level1 backtest fills inside the candle
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.
2026-06-01 20:46:07 +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 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