Files
StockSharp/Algo/Level1ExtendBuilderAdapter.cs
T
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

275 lines
7.0 KiB
C#

namespace StockSharp.Algo;
/// <summary>
/// Level1 extend builder adapter.
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="Level1ExtendBuilderAdapter"/>.
/// </remarks>
/// <param name="innerAdapter">Inner message adapter.</param>
public class Level1ExtendBuilderAdapter(IMessageAdapter innerAdapter) : MessageAdapterWrapper(innerAdapter)
{
private class Level1Info(MarketDataMessage origin)
{
//public readonly HashSet<DataType> AllowedSources = new HashSet<DataType>
//{
// DataType.Ticks,
// DataType.MarketDepth,
// DataType.CandleTimeFrame,
//};
public MarketDataMessage Origin { get; } = origin ?? throw new ArgumentNullException(nameof(origin));
public SubscriptionStates State { get; set; }
}
private readonly Lock _syncObject = new();
private readonly Dictionary<long, Level1Info> _level1Subscriptions = [];
/// <inheritdoc />
public override ValueTask SendInMessageAsync(Message message, CancellationToken cancellationToken)
{
switch (message.Type)
{
case MessageTypes.Reset:
{
using (_syncObject.EnterScope())
_level1Subscriptions.Clear();
break;
}
case MessageTypes.MarketData:
{
var mdMsg = (MarketDataMessage)message;
if (mdMsg.IsSubscribe)
{
if (mdMsg.SecurityId == default)
break;
if (mdMsg.BuildMode == MarketDataBuildModes.Load)
break;
if (mdMsg.DataType2 != DataType.Level1 || mdMsg.To != null)
break;
var transId = mdMsg.TransactionId;
mdMsg = mdMsg.TypedClone();
mdMsg.DataType2 = mdMsg.BuildFrom ?? DataType.MarketDepth;
mdMsg.BuildFrom = null;
using (_syncObject.EnterScope())
_level1Subscriptions.Add(transId, new Level1Info(mdMsg.TypedClone()));
message = mdMsg;
break;
}
else
{
var id = mdMsg.OriginalTransactionId;
using (_syncObject.EnterScope())
{
if (_level1Subscriptions.TryGetAndRemove(id, out var info))
info.State = info.State.ChangeSubscriptionState(SubscriptionStates.Stopped, id, this);
}
break;
}
}
}
return base.SendInMessageAsync(message, cancellationToken);
}
private async ValueTask<TMessage> TryConvertAsync<TMessage>(TMessage subscrMsg, DataType dataType, Func<TMessage, Level1ChangeMessage> convert, CancellationToken cancellationToken)
where TMessage : ISubscriptionIdMessage
{
if (subscrMsg is null)
throw new ArgumentNullException(nameof(subscrMsg));
List<long> subscriptions = null;
List<long> leftSubscriptions = null;
using (_syncObject.EnterScope())
{
if (_level1Subscriptions.Count == 0)
return subscrMsg;
var ids = subscrMsg.GetSubscriptionIds();
foreach (var id in ids)
{
if (!_level1Subscriptions.TryGetValue(id, out var info) || info.Origin.DataType2 != dataType)
{
leftSubscriptions ??= [];
leftSubscriptions.Add(id);
continue;
}
subscriptions ??= [];
subscriptions.Add(id);
}
}
if (subscriptions == null)
return subscrMsg;
var level1 = convert(subscrMsg);
level1.SetSubscriptionIds([.. subscriptions]);
await base.OnInnerAdapterNewOutMessageAsync(level1, cancellationToken);
if (leftSubscriptions == null)
return default;
subscrMsg.SetSubscriptionIds([.. leftSubscriptions]);
return subscrMsg;
}
/// <inheritdoc />
protected override async ValueTask OnInnerAdapterNewOutMessageAsync(Message message, CancellationToken cancellationToken)
{
switch (message.Type)
{
case MessageTypes.SubscriptionResponse:
{
var responseMsg = (SubscriptionResponseMessage)message;
var id = responseMsg.OriginalTransactionId;
using (_syncObject.EnterScope())
{
if (!_level1Subscriptions.TryGetValue(id, out var info))
break;
if (responseMsg.IsOk())
info.State = info.State.ChangeSubscriptionState(SubscriptionStates.Active, id, this);
else
{
_level1Subscriptions.Remove(id);
info.State = info.State.ChangeSubscriptionState(SubscriptionStates.Error, id, this);
}
}
break;
}
case MessageTypes.SubscriptionFinished:
{
var id = ((SubscriptionFinishedMessage)message).OriginalTransactionId;
using (_syncObject.EnterScope())
{
if (_level1Subscriptions.TryGetAndRemove(id, out var info))
info.State = info.State.ChangeSubscriptionState(SubscriptionStates.Finished, id, this);
}
break;
}
case MessageTypes.SubscriptionOnline:
{
var id = ((SubscriptionOnlineMessage)message).OriginalTransactionId;
using (_syncObject.EnterScope())
{
if (_level1Subscriptions.TryGetValue(id, out var info))
info.State = info.State.ChangeSubscriptionState(SubscriptionStates.Online, id, this);
}
break;
}
//case MessageTypes.Level1Change:
//{
// var level1Msg = (Level1ChangeMessage)message;
// using (_syncObject.EnterScope())
// {
// if (_level1Subscriptions.Count == 0)
// break;
// bool? hasBestQuote = null;
// bool? hasLastTrade = null;
// bool? hasCandle = null;
// foreach (var id in level1Msg.GetSubscriptionIds())
// {
// if (!_level1Subscriptions.TryGetValue(id, out var info))
// continue;
// var sources = info.AllowedSources;
// if (sources.Contains(DataType.MarketDepth))
// {
// hasBestQuote ??= level1Msg.IsContainsQuotes();
// if (hasBestQuote == true)
// sources.Remove(DataType.MarketDepth);
// }
// if (sources.Contains(DataType.Ticks))
// {
// hasLastTrade ??= level1Msg.IsContainsTick();
// if (hasLastTrade == true)
// sources.Remove(DataType.Ticks);
// }
// if (sources.Contains(DataType.CandleTimeFrame))
// {
// hasCandle ??= level1Msg.IsContainsCandle();
// if (hasCandle == true)
// sources.Remove(DataType.CandleTimeFrame);
// }
// }
// }
// break;
//}
case MessageTypes.QuoteChange:
{
var quotesMsg = (QuoteChangeMessage)message;
if (quotesMsg.State != null)
break;
message = await TryConvertAsync(quotesMsg, DataType.MarketDepth, Extensions.ToLevel1, cancellationToken);
break;
}
case MessageTypes.Execution:
{
var execMsg = (ExecutionMessage)message;
if (execMsg.DataType != DataType.Ticks)
break;
message = await TryConvertAsync(execMsg, DataType.Ticks, Extensions.ToLevel1, cancellationToken);
break;
}
case MessageTypes.CandleTimeFrame:
{
var candleMsg = (TimeFrameCandleMessage)message;
message = await TryConvertAsync(candleMsg, candleMsg.DataType, Extensions.ToLevel1, cancellationToken);
break;
}
}
if (message != null)
await base.OnInnerAdapterNewOutMessageAsync(message, cancellationToken);
}
/// <summary>
/// Create a copy of <see cref="Level1ExtendBuilderAdapter"/>.
/// </summary>
/// <param name="cancellationToken"><see cref="CancellationToken"/></param>
/// <returns>Copy.</returns>
public override async ValueTask<IMessageAdapter> CloneAsync(CancellationToken cancellationToken)
=> new Level1ExtendBuilderAdapter(await InnerAdapter.CloneAsync(cancellationToken));
}