19 Commits
Author SHA1 Message Date
mika@stocksharp.com 6e7a7dae22 Move instrument lookups and persistence to async
Instrument lookups, configuration, credentials, CSV entities, snapshots and
the alert processing service are read and written asynchronously; the
blocking synchronous forms are obsolete wrappers.

IAsyncPersistable replaces IPersistable: every type that saves and loads its
settings has LoadAsync and SaveAsync only, and nested objects are read with
GetValueAsync, LoadEntireAsync and LoadAllAsync. The synchronous Load and Save
are the obsolete Ecng extensions. The MultiConnect sample keeps IPersistable
for two settings classes, because the settings window of the published
StockSharp.Xaml package takes it.

Copies that were made by saving and loading are made asynchronously.
IMessageAdapter, IIndicator, the risk, commission, PnL, latency, slippage and
position managers, IStorageBuffer, Strategy, DiagramElement, ICompositionModel
and its nodes get CloneAsync and no longer implement ICloneable; Clone is an
obsolete blocking wrapper. A strategy copy keeps every security and portfolio
parameter the original holds. Messages, FieldMapping, BankDetails and
WithdrawInfo are copied in memory. A CommissionRuleMessage shares its rule and
the emulator takes a copy of it. Envelope gets a constructor that takes all
three lines and CreateAsync.

ToBruteForce and ToBruteForceRandom become ToBruteForceAsync and
ToBruteForceRandomAsync and return IAsyncEnumerable; BruteForceOptimizer runs
over it and takes the next strategy through an asynchronous delegate.

Diagram elements keep their own state in SaveState, OnLoading and LoadState.
Undo restores an in-memory snapshot; a chart element holds its series and
axes in it by reference. An alert rule keeps its value in the form a message
carries it. A diagram strategy applies composition settings that were loaded
before the composition was set in SetCompositionAsync or at the start, and
saves them while they wait.

Strategies get an OnStartedAsync hook; diagram strategies resolve securities,
underlyings and strikes before the start so value processing never looks up
instruments. Paths.Serialize, SerializeInvariant, AppStartSettings.TrySave,
ICredentialsProvider.Save, ISnapshotSerializer.Serialize and the composition
registry gain async forms.

ICredentialsProvider.Delete becomes DeleteAsync, so loading, saving and
deleting the credentials wait for one another. Paths.InstalledVersion and
AppNameWithVersion are obsolete in favour of GetInstalledVersionAsync and
GetAppNameWithVersionAsync.

A file is opened for writing only after the last cancellation check, because
opening it empties it; a cancelled read reports the cancellation instead of
an empty result. A snapshot flush that failed leaves what it took due for the
next one.

The indicator templates for C#, F# and Python override LoadAsync and
SaveAsync.
2026-10-04 11:28:17 +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 9519ed8eba Give a named drawing an address something other than WPF can read
The address built for a type's drawing is a pack:// one, and only WPF registers that
scheme: off WPF it cannot even be parsed, so asking a type for its icon threw
UriFormatException rather than answering. Every utility of the data collector names
its picture that way, so its list of utilities came up blank and the panel that shows
a running job threw on the way up.

The same drawing is now also offered in the form a logo attribute already uses - a
path relative to the assembly that carries it - which both platforms can resolve.
WPF keeps asking for the pack form, which is what it wants. Both forms are built from
the one place the file is named, and the path form has tests of its own.
2026-10-01 00:21:38 +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 5d2b2caf25 Correct message and entity contracts 2026-09-12 18:50:59 +03:00
mika@stocksharp.com 0215b8b980 Say what the core promises, in tests that can fail
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
2026-09-12 11:36:47 +03:00
mika@stocksharp.com bdea835aad Add GetAnsweredSubscriptionIds message extension
GetSubscriptionIds answers only for messages tagged with a subscription. A reply
that carries no such tag names just OriginalTransactionId - the transaction of the
request it answers - and that transaction is the subscription it belongs to. The
new extension covers all three cases over Message, so a dispatcher can ask one
question instead of unfolding the interfaces itself.

Null is rejected as by the neighbouring GetSubscriptionIds and HasSubscriptionId:
a message being dispatched is never absent, so a null is a caller defect and must
surface rather than pass for "answers nothing".
2026-08-31 03:56:44 +03:00
mika@stocksharp.com 6219bd8183 Read back the rouble under the name MICEX writes it
ToMicexCurrencyName writes RUB as SUR, which is the name MICEX uses, but
FromMicexCurrencyName only tried to parse the enum, so the one value the pair
special-cases could not be read back and every MICEX security was left without
a currency. The exchange names the rouble in more than one way, and only one of
them is the ISO code the enum carries, so the others are mapped rather than
left to fail parsing.

Covered by tests for both directions, the two aliases, and a round trip.
2026-08-20 01:37:15 +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 c02516687b Tests: strengthen ApplyNewBalance and LoopBack, drop malformed-book Join characterization
Assert ApplyNewBalance return values plus the exact error log level and message content. Implement the
previously stubbed LoopBack test with a recording adapter, asserting back mode, adapter and IsBack.
Remove the Join duplicate-price test that only characterized behavior on a malformed book with two
quotes at the same price; the distinct-price merge/sort and empty-rare cases remain covered.
2026-06-19 01:22:09 +03:00
mikasoukhov 23b8986b3b WorkingTime moved to Ecng. 2026-02-11 00:19:53 +03:00
mikasoukhov beac667ab1 Code cleanup. 2026-02-06 16:02:46 +03:00
mikasoukhov 364478b5a8 Fix MakeVectorIconUri test. 2026-02-06 09:26:41 +03:00
mikasoukhov d2e3d11df2 Small changes. 2026-02-01 17:05:22 +03:00
mikasoukhov a199c535cf More tests. 2026-02-01 10:43:24 +03:00
mikasoukhov bc4aecef07 More tests. 2026-01-28 19:48:14 +03:00
mikasoukhov f5a6017940 Add Tier 3 extension method tests (8 new, 111 total)
ToReadableString (2), Join OrderBook (2), IsHalfEmpty (4)
2026-01-28 11:56:29 +03:00
mikasoukhov cfb7bb61cb Add Tier 2 extension method tests (34 new, 103 total)
ToReg/ToExec roundtrip (3), IsCanceled/IsMatched/Partially/Empty (8),
ApplyNewBalance (3), SafeGetVolume (3), IsAllSecurity (3),
IsLookupAll (3), ToMessageType2 (5), GetPlazaTimeInForce (4),
LastTradeDay (2)
2026-01-28 11:50:09 +03:00
mikasoukhov 644dcee9fe Add ExtensionsMethodsTests for Tier 1 extension methods (69 tests)
Tests for: GetSpreadMiddle (9), ShrinkPrice (5), Iso10962 (15),
GetOrderLogCancelReason (4), CreateErrorResponse (3), ToOrderSnapshot (4),
AddDelta (6), Group (4), IsTradeTime (4), AddOrSubtractTradingDays (3),
DecodeToPeriods/EncodeToString (2)
2026-01-28 11:41:33 +03:00