Files
StockSharp/Algo.Testing/BaseEmulationConnector.cs
mika@stocksharp.com 4203be8f5c Unwind the blocking waits left by the async rework and fix what it uncovered
"Mark the blocking wrappers obsolete" left several callers of those wrappers
under #pragma, because a property, a parameter handler or a state setter could
not wait, and a few places that blocked without a wrapper. Each of those
chains now runs through callers that can await.

The emulation connector. A state change collects what its handlers throw and
sends it out once the state lock is released; the disconnect that follows
Stopping is awaited there as well. The change to Stopped moved from a handler
of Disconnected into OnDisconnectedAsync, a step the connector now awaits
before it raises that event.

ExpressionIndexSecurity. Expression records the text and reads the instruments
it names, which needs no compiler. The formula is compiled by GetFormulaAsync;
Formula is an obsolete blocking wrapper over it. IBasketSecurityProcessor gets
InitAsync, where the expression processor takes its formula, and
CreateProcessorAsync creates a processor and prepares it; CreateProcessor and
the IEnumerable ToBasket are obsolete wrappers, and the tests of ToBasket go
through the IAsyncEnumerable overload. The index diagram element builds its
index in OnPrepareAsync.

MathDiagramElement. The inputs are named by the text of the formula; the
formula and its validation are compiled in OnPrepareAsync. An element that was
reset therefore compiles again at the next start instead of refusing to start.
An input that is wired stays while the text is not known to compile, and goes
at the preparation if the compiled formula does not name it. A text replaced
under a running element is an error on every value until the element is
prepared again.

Candle patterns. A CandleExpressionCondition compiled its formula in the
constructor or, for the registry, at the first evaluation. The formula is now
compiled by PrepareAsync: on the condition, on ICandlePattern and, through the
new IIndicator.PrepareAsync, on the indicator that holds a pattern. A pattern
that was not prepared refuses to recognize instead of compiling on the spot.
The checks of a pattern as a whole - a formula reaching outside it, no
formulas at all - moved from the first Recognize to the preparation, and a
failed check no longer leaves the pattern marked as checked. Whoever feeds an
indicator prepares it first: IndicatorDiagramElement in OnPrepareAsync, a
strategy for the indicators its start registered, the chart samples when an
indicator is added. ICandlePatternProvider.Save became SaveAsync and prepares
the pattern before it stores it. The compileOnDemand constructor is gone: no
constructor compiles.

Stopping a strategy from code that cannot wait. When an element was entered
deeper than the overflow limit, DiagramElement.Process stopped the strategy
through AsyncHelper.Run. Strategy gets RequestStop for such code: it reports
the error, refuses new orders at once and leaves the stop itself to
OnNewMessage, which carries it out when the connector hands over the next
message.

Releasing a connector. Connector.DisposeManaged waited for the disconnect, and
for the message that takes the adapters apart, through AsyncHelper.Run. The
release is now DisposeManagedAsync, a virtual chain that the connectors
derived from Connector override. DisposeAsync awaits it, and the sealed
DisposeManaged is the same chain with the caller blocked, as IDisposable
requires. IConnector is IAsyncDisposable, so code that holds a connector by
its interface releases it by await as well.

Diagram elements that waited for their type. A composition read before one of
its element types was registered keeps an empty node for each such element.
Registering the type started their load unawaited, and a failure lost the
settings at the next save. ICompositionRegistry gets
LoadNotLoadedElementsAsync, to be awaited by whoever registered the types. It
loads what waits in the given composition and in the compositions nested in
it, one call at a time. The settings of an element that waits are kept by its
node (ICompositionModelNode.ElementSettings). A loaded element joins its
model: it is announced as an added one and the links of its node are
connected.

The sample windows. CombineHistoryRealtime, LiveTerminal and StoreDataLocal,
WPF and Avalonia, flushed the storage executor, released the CSV registries
and read them at startup through AsyncHelper.Run. A window now refuses the
first attempt to close it, awaits the release and closes itself once the
queued writes are on the disk. A shutdown that does not honour the refusal -
the end of the Windows session, Application.Shutdown - is not waited for: what
is still queued then is lost. LiveOptionsQuoting and MultiConnect called the
blocking Strategy.Start, Stop and GetTimeFrames under a suppressed obsolete
warning; they await the async ones now.

What the rework uncovered:

- Pausing the optimizer. An iteration that had passed the pause gate but
  whose connector had not started replaying yet ran to its end through the
  pause; cloning the strategy asynchronously made that window long enough for
  PauseHaltsBruteForce to see it on CI. An iteration now waits for its
  connector to come up and suspends it if the optimizer is paused by then.
- Undo of diagram elements. An undo scope opened with no undo manager in
  sight took the element's level down when it closed, so the level was
  negative by the time the element reached a composition and no edit was ever
  reported. The scope remembers whether it was counted.
- Undo of a chart panel. A snapshot keeps the series and axes of a panel by
  reference, since a part can only be saved asynchronously, so undo did not
  put back what a part was set to. IChartSnapshotPart is an optional interface
  for a part that can copy its settings in memory; the panel captures and
  gives back the settings of such parts. No chart part implements it yet -
  that is for the chart packages to do.
- The dummy indicator wrapper was left without a chart element, so indicator
  values could not be wired into the panel that a run without a window uses.
- Settings loaded before a composition existed are applied when the strategy
  starts; a test pins it.
- AsyncMessageChannel looked at its state once per wake-up and then went
  through the queue until it was empty, so a message sent right after Suspend
  returned could still be started, and Suspend_PausesProcessing was red from
  time to time. The state is now read under the queue lock, where the next
  message is picked; a channel that is being closed stops starting what is
  queued the same way.

DiagramElementParamTests no longer declares a value that persists itself
through the obsolete IPersistable: declaring one needs a suppressed warning,
and for that contract the parameter relies on SaveEntireAsync and
LoadEntireAsync of Ecng, which are tested there.
2026-10-04 18:59:25 +03:00

176 lines
6.0 KiB
C#

namespace StockSharp.Algo.Testing;
using StockSharp.Algo.Testing.Generation;
/// <summary>
/// The base connection of emulation.
/// </summary>
public abstract class BaseEmulationConnector : Connector
{
/// <summary>
/// Initializes a new instance of the <see cref="BaseEmulationConnector"/>.
/// </summary>
/// <param name="emulationAdapter">Emulation message adapter.</param>
/// <param name="applyHeartbeat">Apply on/off heartbeat mode for the specified adapter.</param>
/// <param name="initChannels">Initialize channels.</param>
protected BaseEmulationConnector(EmulationMessageAdapter emulationAdapter, bool applyHeartbeat, bool initChannels)
: base(
new InMemorySecurityStorage(emulationAdapter.CheckOnNull(nameof(emulationAdapter)).Emulator.SecurityProvider),
new InMemoryPositionStorage(emulationAdapter.Emulator.PortfolioProvider),
emulationAdapter.Emulator.ExchangeInfoProvider, initChannels: initChannels)
{
Adapter.InnerAdapters.Add(emulationAdapter ?? throw new ArgumentNullException(nameof(emulationAdapter)));
Adapter.ApplyHeartbeat(EmulationAdapter, applyHeartbeat);
Adapter.IsSupportTransactionLog = emulationAdapter.IsSupportTransactionLog;
TimeChange = false;
// sync transaction ids with underlying adapter
TransactionIdGenerator = emulationAdapter.TransactionIdGenerator;
}
/// <inheritdoc />
public override IEnumerable<Portfolio> Portfolios => base.Portfolios.Concat(EmulationAdapter.Emulator.PortfolioProvider.Portfolios).Distinct();
private DateTime _currentTime;
/// <inheritdoc />
public override DateTime CurrentTime => _currentTime;
/// <inheritdoc />
public override bool UnsubscribeOnDisconnect => false;
/// <summary>
/// The adapter, executing messages in <see cref="IMarketEmulator"/>.
/// </summary>
public EmulationMessageAdapter EmulationAdapter => (EmulationMessageAdapter)Adapter.InnerAdapters.First();
/// <inheritdoc />
public override async Task LoadAsync(SettingsStorage storage, CancellationToken cancellationToken)
{
if (EmulationAdapter.OwnInnerAdapter)
await EmulationAdapter.LoadAsync(storage, nameof(EmulationAdapter), cancellationToken);
await base.LoadAsync(storage, cancellationToken);
}
/// <inheritdoc />
public override async Task SaveAsync(SettingsStorage storage, CancellationToken cancellationToken)
{
if (EmulationAdapter.OwnInnerAdapter)
storage.SetValue(nameof(EmulationAdapter), await EmulationAdapter.SaveAsync(cancellationToken));
await base.SaveAsync(storage, cancellationToken);
}
/// <inheritdoc />
protected override ValueTask OnProcessMessage(Message message, CancellationToken cancellationToken)
{
// output messages from adapters goes non ordered
if (_currentTime < message.LocalTime)
_currentTime = message.LocalTime;
return base.OnProcessMessage(message, cancellationToken);
}
/// <inheritdoc />
public override async ValueTask ClearCacheAsync(CancellationToken cancellationToken)
{
await base.ClearCacheAsync(cancellationToken);
_currentTime = default;
}
/// <inheritdoc />
protected override async ValueTask DisposeManagedAsync()
{
if (EmulationAdapter.OwnInnerAdapter)
EmulationAdapter.Dispose();
await base.DisposeManagedAsync();
}
/// <summary>
/// To register the trades generator.
/// </summary>
/// <param name="generator">The trades generator.</param>
/// <returns>Subscription.</returns>
//[Obsolete("Uses custom adapter implementation.")]
public Subscription RegisterTrades(TradeGenerator generator)
=> SubscribeGenerator(generator);
/// <summary>
/// To delete the trades generator, registered earlier through <see cref="RegisterTrades"/>.
/// </summary>
/// <param name="generator">The trades generator.</param>
[Obsolete("Uses UnSubscribe method.")]
public void UnRegisterTrades(TradeGenerator generator)
=> UnSubscribeGenerator(generator);
/// <summary>
/// To register the order books generator.
/// </summary>
/// <param name="generator">The order books generator.</param>
/// <returns>Subscription.</returns>
//[Obsolete("Uses custom adapter implementation.")]
public Subscription RegisterMarketDepth(MarketDepthGenerator generator)
=> SubscribeGenerator(generator);
/// <summary>
/// To delete the order books generator, earlier registered through <see cref="RegisterMarketDepth"/>.
/// </summary>
/// <param name="generator">The order books generator.</param>
[Obsolete("Uses UnSubscribe method.")]
public void UnRegisterMarketDepth(MarketDepthGenerator generator)
=> UnSubscribeGenerator(generator);
/// <summary>
/// To register the orders log generator.
/// </summary>
/// <param name="generator">The orders log generator.</param>
/// <returns>Subscription.</returns>
//[Obsolete("Uses custom adapter implementation.")]
public Subscription RegisterOrderLog(OrderLogGenerator generator)
=> SubscribeGenerator(generator);
/// <summary>
/// To delete the orders log generator, earlier registered through <see cref="RegisterOrderLog"/>.
/// </summary>
/// <param name="generator">The orders log generator.</param>
[Obsolete("Uses UnSubscribe method.")]
public void UnRegisterOrderLog(OrderLogGenerator generator)
=> UnSubscribeGenerator(generator);
private Subscription SubscribeGenerator(MarketDataGenerator generator)
{
if (generator == null)
throw new ArgumentNullException(nameof(generator));
var subscription = new Subscription(new GeneratorMessage
{
TransactionId = TransactionIdGenerator.GetNextId(),
IsSubscribe = true,
SecurityId = generator.SecurityId,
Generator = generator,
DataType2 = generator.DataType,
});
Subscribe(subscription);
return subscription;
}
private void UnSubscribeGenerator(MarketDataGenerator generator)
{
if (generator is null)
throw new ArgumentNullException(nameof(generator));
var subscription = Subscriptions.FirstOrDefault(s => s.SubscriptionMessage is GeneratorMessage genMsg && genMsg.Generator == generator);
if (subscription != null)
UnSubscribe(subscription);
else
LogWarning(LocalizedStrings.SubscriptionNonExist, generator);
}
}